我在功能应用程序组件中使用useEffect((钩子来检查身份验证是否已过期,这样我就可以调度一个操作来删除持久的身份验证状态(使用redux-persistent(。下面是代码:
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的另一个组件中使用它。
这只是一个拼写错误。我忘记给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;