React @redux/toolkit 更新状态时不重新渲染组件
React @redux/toolkit not re-rendering component when state is updated
Codesandbox:https://codesandbox.io/s/condescending-wiles-funk0?file=/src/App.js
问题:当我更新商店状态时,组件没有重新呈现。在上面的示例中,您可以从控制台看到数据已正确获取,但组件未重新渲染并继续渲染 Loading...
.
预期行为:当我更新状态时,组件被重新渲染。
我通过在组件中使用 useState 并订阅存储更改找到了解决方法,例如:
store.subscribe(() => setComponentState(store.getData())
这基本上会在每次更新数据时强制重新渲染。
我可以改变状态:在官方文档中,他们说你可以改变状态,因为它有一些允许这样做的魔法(https://redux-toolkit.js.org/usage/usage-guide#simplifying-reducers-with-createreducer),因此这不是问题。
有人知道什么是让它发挥作用的合适方法吗?
来自 useStore docs,它声明不应在应用程序中使用挂钩,因为它不会导致组件重新呈现:
// EXAMPLE ONLY! Do not do this in a real app.
// The component will not automatically update if the store state changes
相反,您应该使用 useSelector。
关于这一点,您的 codesandbox 示例将导致无限重新渲染,因为每次更新 redux 状态时都会调用 dispatch(fetchData());
。相反,您需要将其放在 React.useEffect
.
内
例如,使用 useSelector
和 useEffect
:
在 Github 上得到了答案:https://github.com/reduxjs/redux-toolkit/issues/942#issuecomment-807813092
You should not be using the useStore hook. You should be using the
useSelector hook, which subscribes to store updates:
Codesandbox:https://codesandbox.io/s/condescending-wiles-funk0?file=/src/App.js
问题:当我更新商店状态时,组件没有重新呈现。在上面的示例中,您可以从控制台看到数据已正确获取,但组件未重新渲染并继续渲染 Loading...
.
预期行为:当我更新状态时,组件被重新渲染。
我通过在组件中使用 useState 并订阅存储更改找到了解决方法,例如:
store.subscribe(() => setComponentState(store.getData())
这基本上会在每次更新数据时强制重新渲染。
我可以改变状态:在官方文档中,他们说你可以改变状态,因为它有一些允许这样做的魔法(https://redux-toolkit.js.org/usage/usage-guide#simplifying-reducers-with-createreducer),因此这不是问题。
有人知道什么是让它发挥作用的合适方法吗?
来自 useStore docs,它声明不应在应用程序中使用挂钩,因为它不会导致组件重新呈现:
// EXAMPLE ONLY! Do not do this in a real app.
// The component will not automatically update if the store state changes
相反,您应该使用 useSelector。
关于这一点,您的 codesandbox 示例将导致无限重新渲染,因为每次更新 redux 状态时都会调用 dispatch(fetchData());
。相反,您需要将其放在 React.useEffect
.
例如,使用 useSelector
和 useEffect
:
在 Github 上得到了答案:https://github.com/reduxjs/redux-toolkit/issues/942#issuecomment-807813092
You should not be using the useStore hook. You should be using the useSelector hook, which subscribes to store updates: