reactjs - 在 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?
解决方案
您可以使用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;
}
推荐阅读
- python - 使用 SQLAlchemy 反映的 Postgres 表无法识别加入的列
- css - css 过渡在 vuejs 中无法正常工作
- homebrew - 无法在 BigSur 上安装 Homebrew “登录被拒绝”
- android - 如何在 RecyclerView 的 TextView 中显示带有 JPG 和 GIF 图像的 html 内容?
- lua - 如何根据玩家的方向偏移子弹对象
- highcharts - Highcharts 导航器鼠标悬停不工作
- php - 从本地表单发布到 App Engine 托管的 PHP 脚本
- python - 如何从经过训练的神经网络中可视化嵌入?
- python - 在python中获取某个子字符串之后的前X个字符+子字符串
- reactjs - 页面恢复时如何将数据保留在反应组件中