Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

reactjs - React get state from Redux store within useEffect

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...