Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - Redux state variable undefined in useEffect return function

A variable fetched from Redux state by useSelector is undefined in useEffect return function:

const ExampleComponent = () => {
    const dispatch = useDispatch();

    const stateVariable = useSelector(state => state.variable);
    console.log(stateVariable) // undefined on first render, then "whatever"

    useEffect(() => {
        // set state on component mount using a generic action creator
        dispatch(setStateVariable("whatever")); 
        
        return () => {
            console.log(stateVariable) // undefined on unmount
        }
    }, []); // leave empty so it runs only on mount/unmount

    return null;
}

Why is stateVariable undefined in the cleanup function? How can I use stateVariable in the cleanup function?

question from:https://stackoverflow.com/questions/65863159/redux-state-variable-undefined-in-useeffect-return-function

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

1 Reply

0 votes
by (71.8m points)

you can anchor your value using useRef to have access to its value on cleanup function. You get undefined because of closure, where your function saves the reference value once is declared:

const ExampleComponent = () => {
  const dispatch = useDispatch();

  const stateVariable = useSelector(state => state.variable);
  const stateRef = useRef();
  stateRef.current = stateVariable;
  console.log(stateVariable); // undefined on first render, then "whatever"

  useEffect(() => {
      // set state on component mount using a generic action creator
      dispatch(setStateVariable("whatever")); 
      
      return () => {
          console.log(stateRef.current);
      }
  }, []); // leave empty so it runs only on mount/unmount

  return null;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...