是什么导致redux状态加载延迟?

时间:2020-09-15 18:08:07

标签: javascript reactjs redux react-redux

我有一个简单的占位符组件,仅显示加载屏幕。但是在后台,它正在进行检查以将其重定向到正确的路径。使用react-redux,我可以选择处于我自己状态的属性。

  const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
  console.log(isAuthenticated)
    useEffect(() => {
        if (isAuthenticated) {
          history.push("/home");
        } else {
          history.push("/login");
        }
      }, [isAuthenticated, history]);

   return (
       <Spin size="large" />
   );

// Redux存储配置

const configureStore = (persistedState) => {
  const store = createStore(
    rootReducer,
    persistedState,
    applyMiddleware(thunkMiddleware)
  );
  store.dispatch(validateAuth());
  return store;
};

但是当我检查控制台时,下面的输出显示它可能正在加载初始状态,然后是更新状态。是什么原因导致此延迟?由于它总是重定向到/ login

enter image description here

1 个答案:

答案 0 :(得分:0)

  useEffect(() => {
    const timer = setTimeout(() => {
      if (isAuthenticated) {
        console.log("I'm here")
      } else {
        history.push("/login");
      }
    }, 1000);
    return () => clearTimeout(timer);
  }, [isAuthenticated, history]);

我决定将useEffect操作包装在一个超时中,以等待正确的状态被加载。如果这不正确或不是最佳做法,请让我知道更好的答案。

相关问题