[英]React @redux/toolkit not re-rendering component when state is updated
代码沙盒: https://codesandbox.io/s/condescending-wiles-funk0?file=/src/App.js
问题:当我更新商店的 state 时,组件不会重新渲染。 在上面的示例中,您可以从控制台看到数据已正确获取,但组件没有重新渲染并继续渲染只是Loading...
。
预期行为:当我更新 state 时,组件被重新渲染。
我通过在组件中使用 useState 并订阅存储更改找到了一种解决方法,例如:
store.subscribe(() => setComponentState(store.getData())
这基本上会在每次更新数据时强制重新渲染。
I can mutate state : In the official docs they say that you can mutate the state since it has some magic that allows to do so ( https://redux-toolkit.js.org/usage/usage-guide#simplifying-reducers- with-createreducer ),因此这不是问题。
任何人都知道什么是使它工作的适当方法?
从useStore docs ,它指出钩子不应该在应用程序中使用,因为它不会导致组件重新渲染:
// 仅示例。 不要在真正的应用程序中执行此操作。
// 如果存储区 state 发生变化,组件不会自动更新
相反,您应该改用useSelector 。
在那一点上,您如何拥有您的代码框示例将导致自dispatch(fetchData());
每次更新 redux state 时都会调用。 相反,您需要将它放在React.useEffect
中。
例如,将useSelector
与useEffect
一起使用:
得到了关于 Github 的答案: https://github.com/reduxjs/redux-toolkit/issues/942#issuecomment-807813092
您不应该使用 useStore 挂钩。 您应该使用订阅商店更新的 useSelector 钩子:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.