首页 > 解决方案 > Redux:为什么 store.getState() 与 useSelector 返回不同的值?

问题描述

我有一个自定义钩子,用于从我的 redux 存储中获取值并在各种组件中使用它。

在下面的代码中,您将看到我用于useCustomHook从 redux 返回数据和加载状态。但由于某种原因,该值似乎总是滞后一个渲染周期。

例如,当单击按钮时,我希望立即看到dataLoadinginMyComponent更新,但事实并非如此。当我对此进行检查时,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方法中它没有。

标签: javascriptreactjsreact-redux

解决方案


推荐阅读