首页 > 解决方案 > 在 useEffect 返回函数中未定义 Redux 状态变量

问题描述

通过 useSelector 从 Redux 状态获取的变量在 useEffect 返回函数中未定义:

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;
}

为什么清理函数中未定义 stateVariable?如何在清理功能中使用 stateVariable?

标签: reactjsreact-reduxreact-hooks

解决方案


您可以使用useRef来锚定您的价值,以便在清理功能上访问其价值。你得到undefined因为闭包,你的函数在声明一次时保存引用值:

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;
}

推荐阅读