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?
答案 0 :(得分:2)
您可以使用 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;
}