javascript - useSelector 不会像 Redux 中的 connect 那样重新渲染组件
问题描述
我试图搜索这个问题,但大部分主题都是关于 mutate 但在我的情况下它是一个原始数据类型,这里是示例代码:
// ParentPage.jsx
import { useSelector } from 'react-redux';
const selectShowFooterFlag = (state) => {
return state.shouldShowFooter;
}
const ParentPage = () => {
const shouldShowFooter = useSelector(selectShowFooterFlag);
const ChildComponent = useSelector(selectChildComponent);
return (
<p>{String(shoudShowFooter)}</p>
<ChildComponent shoudShowFooter={shoudShowFooter}>
)
}
export default ParentPage;
// ChildPage
const ChildPage = ({ shoudShowFooter }) => {
useEffect(() => {
dispatch(shouldShowFooterState(false));
return () => {
dispatch(shouldShowFooterState(true));
}
});
return (
<p>String(shoudShowFooter)</p>
)
}
// reducer
const initalState = {
isPageFooterRequired: true,
};
export const pagesReducer: (draft, action) = produce((draft = initialState, action: DispatchAction) => {
switch() {
case SHOW_FOOTER:
draft.shoudShowFooter = action.payload;
break;
default:
return draft;
}
});
在此示例中,当子组件挂载时,它将shoudShowFooter
按false
预期设置。在ChildComponent
redux 存储中更新时,当前 ChildComponent 将卸载并将其设置shoudShowFooter
为true
. 我已经检查过了,它是正确的(selectShowFooterFlag
已被调用)。
但问题是shoudShowFooter
redux 发生了变化,但ParentPage
没有使用新状态重新渲染,因此新的 ChildComponent 无法接收 reducer 存储中的最新数据(我已经检查了 Redux devtools 的最新状态数据)。
更有趣的一点是,当我切换到使用 connect 时,一切正常。
import { connect } from 'react-redux';
const selectShowFooterFlag = (state) => {
return state.shouldShowFooter;
}
const ParentPage = () => {
const ChildComponent = useSelector(selectChildComponent);
return (
<p>{String(shoudShowFooter)}</p>
<ChildComponent shoudShowFooter={shoudShowFooter}>
)
}
const mapStateToProps = (state) => {
return {
shouldShowFooter: selectShowFooterFlag(state);
}
}
export default connect(mapStateToProps)(ParentPage);
我认为 useSelector 会给我们与连接相同的行为,当状态数据发生变化时会重新渲染组件。但似乎不是在这种情况下。
如何useSelector
使用最新数据重新渲染触发器connect
?或者我如何调试这个案例来看看为什么 React 不重新渲染应用程序?
解决方案
推荐阅读
- android - 如何在 API 级别 15 (Android 4.0.3) 上创建 Android (AVD) 模拟器
- python - 在另一个列表中查找包含 5 个连续字符串的单词
- python - 如何使用熊猫系列对条件进行矢量化?
- python - 在 Django 中测试 Url 是否给出 500 错误
- c# - 关闭的表单仍显示在任务栏中
- c# - 请参阅 Unity Inspector 中数组的枚举索引
- c++ - 为什么我的编译器会显示有关我的 constexpr 函数的此错误?
- java - 如何从远程源 (url) 获取图像并在 ImageView 中显示?
- sql-server - 在同一记录中重新插入主键
- ruby-on-rails - Rails 访问模型内模块中的共享自定义验证