javascript - Redux:为什么 store.getState() 与 useSelector 返回不同的值?
问题描述
我有一个自定义钩子,用于从我的 redux 存储中获取值并在各种组件中使用它。
在下面的代码中,您将看到我用于useCustomHook
从 redux 返回数据和加载状态。但由于某种原因,该值似乎总是滞后一个渲染周期。
例如,当单击按钮时,我希望立即看到dataLoading
inMyComponent
更新,但事实并非如此。当我对此进行检查时,store.getState().loading
我得到了正确的值。这是为什么?我在这里没有提到的反应是否存在一些渲染问题?
const useCustomHook = () => {
const data = useSelector(state => state.data)
const dataLoading = useSelector(state => state.loading)
useEffect(() => {
if (!data && !dataLoading) {
dispatch(loadMyDataAction());
}
}, []);
const update = (newData) => {
dispatch(updateData(newData));
}
return {data, dataLoading, update}
}
const MyComponent = () => {
const {data, dataLoading, update} = useCustomHook();
const store = useStore();
const continue = () => {
// Here my data loading doesn't change on click of button.
// but value for store.getStore().loading return the right value
while (dataLoading) {
console.log("waiting for loading to finish");
}
window.location = "https://mynewsite.com"
}
if (dataLoading) {
return (<div>Loading</div>);
}
return (
<div>
<button onClick={() => update(someRandomData)}>Update</button>
<button onClick={() => continue()}>Continue</button>
</div>
)
}
更新:所以在测试dataLoading
了 useEffect 之后,我可以看到加载值在该 useEffect 中发生了变化。但在我的continue
方法中它没有。
解决方案
推荐阅读
- php - 即使使用用户代理,file_get_contents 也会被禁止 403
- javascript - 如何从 html 脚本标签访问 index.js res 属性
- ios - iOS 增强现实 3D 边界框精确尺寸
- cors - Swagger OpenApi 3.0 不允许 PUT 请求仅 POST 和 GET 工作
- docker - Nginx- 502 错误网关
- reactjs - 带有 Netlify CMSField“缩略图”的 Gatsby 图像不能有选择,因为类型“字符串”没有子字段
- javascript - 如何将 url 参数转换为对象数组的对象?
- composer-php - 用户/项目而不是组的 Gitlab Composer 包注册表
- python - Python xlwt - 你能保护工作簿格式吗?
- css - 如何从 VH calc 中获得高度的百分比?