React get state from Redux store within useEffect

五迷三道 提交于 2020-06-27 16:54:51

问题


What is the correct way to get state from the Redux store within the useEffect hook?

    useEffect(() => { 
        const user = useSelector(state => state.user);
    });

I am attempting to get the current state within useEffect but I cannot use the useSelector call because this results in an error stating:

Invariant Violation: Hooks can only be called inside the body of a function component.

I think I understand why as it breaks one of the primary rules of hooks.

From reviewing the example on the Redux docs they seem to use a selectors.js file to gather the current state but this reference the mapStateToProps which I understood was no longer necessary.

Do I need to create some kind of "getter" function which should be called within the useEffect hook?


回答1:


You can place useSelector at the top of your component along with the other hooks:

const MyComponent = () => {
  ...
  const user = useSelector(state => state.user);
  ...
}

Then you can access user inside your useEffects.




回答2:


Don't forget to add user as a dependency to useEffect otherwise your effect won't get updated value.

const user = useSelector(state => state.user);
useEffect(() => { 
   // do stuff     
}, [user]);


来源:https://stackoverflow.com/questions/58159108/react-get-state-from-redux-store-within-useeffect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!