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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…