如何在useEffect()挂钩内使用useDispatch()挂钩?

时间:2020-10-30 15:31:22

标签: reactjs redux react-redux

我正在使用功能性App组件中的useEffect()挂钩来检查身份验证是否已过期,以便我可以调度一个操作来删除持久的身份验证状态(使用redux-persist)。下面是代码:

import React, { useEffect } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { signout } from "./app/state/authSlice";

import Signin from "./app/pages/Signin";
import Landing from "./app/pages/Landing";

const App = (props) => {
  const dispatch = useDispatch();
  const auth = useSelector((state) => state.auth);
  const expired = new Date(Date.now()) >= new Date(auth.expires);
  useEffect(() => {
    const main = () => {
      if (expired) {
        console.log("Auth expired.");
        dispatch(signout);
      }
    };
    main();
  }, [dispatch, expired]);

  return (
    <Router>
      <Switch>
        <Route exact path="/" {...props} component={Landing} />
        <Route exact path="/signin" {...props} component={Signin} />
      </Switch>
    </Router>
  );
};

export default App;

现在,当到期时间过去时,我会收到Auth expired控制台日志,但是调度未发生,并且在到期时间之后我的状态仍然保持。我知道退出操作已正确配置,因为我在另一个组件onClick中使用了退出操作。

1 个答案:

答案 0 :(得分:1)

这只是一个错字。我忘了打电话给signout()动作创建者了。

下面更正代码。

import React, { useEffect } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { signout } from "./app/state/authSlice";

import SigninPage from "./app/pages/Signin";
import LandingPage from "./app/pages/Landing";

const App = (props) => {
  const dispatch = useDispatch();
  const auth = useSelector((state) => state.auth);
  const expired = new Date(Date.now()) >= new Date(auth.expires);
  useEffect(() => {
    const main = () => {
      if (expired) {
        console.log("Auth expired.");
        dispatch(signout());
      }
    };
    main();
  }, [dispatch, expired]);

  return (
    <Router>
      <Switch>
        <Route exact path="/" {...props} component={LandingPage} />
        <Route exact path="/signin" {...props} component={SigninPage} />
      </Switch>
    </Router>
  );
};

export default App;