Should I use useselector/useDispatch instead of mapStateToProps

后端 未结 5 1402
孤街浪徒
孤街浪徒 2021-02-19 00:07
5条回答
  •  攒了一身酷
    2021-02-19 00:29

    For callback functions you can use the value returned from useSelector the same way you would use the value from useState.

    const ExampleComponent = () => {
        // use hook to get data from redux state.
        const stateData = useSelector(state => state.data);
    
        // use hook to get dispatch for redux store.
        // this allows actions to be dispatched.
        const dispatch = useDispatch();
    
        // Create a non-memoized callback function using stateData.
        // This function is recreated every rerender, a change in
        // state.data in the redux store will cause a rerender.
        const callbackWithoutMemo = (event) => {
            // use state values.
            if (stateData.condition) {
                doSomething();
            }
            else {
                doSomethingElse();
            }
    
            // dispatch some action to the store
            // can pass data if needed.
            dispatch(someActionCreator());
        };
    
        // Create a memoized callback function using stateData.
        // This function is recreated whenever a value in the
        // dependency array changes (reference comparison).
        const callbackWithMemo = useCallback((event) => {
            // use state values.
            if (stateData.condition) {
                doSomething();
            }
            else {
                doSomethingElse();
            }
    
            // dispatch some action to the store
            // can pass data if needed.
            dispatch(someActionCreator());
        }, [stateData, doSomething, doSomethingElse]);
    
        // Use the callbacks.
        return (
            <>
                
    Click me
    Click me
    ) };

    Rules of hooks says you must use it at the root of your component, meaning you CANT use it anywhere.

    As Max stated in his answer just means that the hook statement itself must not be dynamic / conditional. This is because the order of the base hooks (react's internal hooks: useState, etc) is used by the backing framework to populate the stored data each render.

    The values from hooks can be used where ever you like.

    While I doubt this will be close to answering your complete question, callbacks keep coming up and no examples had been posted.

提交回复
热议问题