Should I use useselector/useDispatch instead of mapStateToProps

后端 未结 5 1387
孤街浪徒
孤街浪徒 2021-02-19 00:07
5条回答
  •  走了就别回头了
    2021-02-19 00:38

    The redux state returned from the useSelector hook can be passed around anywhere else just like its done for mapStateToProps. Example: It can be passed to another function too. Only constraint being that the hook rules has to be followed during its declaration:

    1. It has to be declared only within a functional component.

    2. During declaration, it can not be inside any conditional block . Sample code below

          function test(displayText) {
             return (
      {displayText}
      ); } export function App(props) { const displayReady = useSelector(state => { return state.readyFlag; }); const displayText = useSelector(state => { return state.displayText; }); if(displayReady) { return (
      Outer {test(displayText)}
      ); } else { return null; } }

    EDIT: Since OP has asked a specific question - which is about using it within a callback, I would like to add a specific code.In summary, I do not see anything that stops us from using useSelector hook output in a callback. Please see the sample code below, its a snippet from my own code that demonstrates this particular use case.

    export default function CustomPaginationActionsTable(props) {
    //Read state with useSelector.
    const searchCriteria = useSelector(state => {
      return state && state.selectedFacets;
     });
    
    //use the read state in a callback invoked from useEffect hook.
    useEffect( ()=>{
      const postParams = constructParticipantListQueryParams(searchCriteria);
      const options = {
        headers: {
            'Content-Type': 'application/json'
        },
        validateStatus: () => true
      };
      var request = axios.post(PORTAL_SEARCH_LIST_ALL_PARTICIPANTS_URI, postParams, options)
          .then(function(response)
            { 
              if(response.status === HTTP_STATUS_CODE_SUCCESS) {
                console.log('Accessing useSelector hook output in axios callback. Printing it '+JSON.stringify(searchCriteria));
                
              }
                        
            })          
          .catch(function(error) {
          });
    }, []);
    }
    

提交回复
热议问题