[英]How to use the useDispatch() hook inside the useEffect() hook?
I am using the useEffect() hook in my functional App component to check if the authentication has expired, so that I can dispatch an action to delete the persisted authentication state (using redux-persist).我在我的功能性 App 组件中使用 useEffect() 钩子来检查身份验证是否已过期,以便我可以调度一个操作来删除持久的身份验证状态(使用 redux-persist)。 below is the code:
下面是代码:
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;
Now, I am getting the Auth expired
console log when the expiry time is past, but the dispatch is not happening and my state still persists after the expiry time.现在,当过期时间过去时,我收到了
Auth expired
控制台日志,但没有发生调度,并且我的状态在过期时间后仍然存在。 I know that the signout action is correctly configured because I am using that in another component onClick.我知道注销操作已正确配置,因为我在另一个组件 onClick 中使用了它。
This was just a typo.这只是一个错字。 I forgot to call the
signout()
action creator.我忘了调用
signout()
动作创建者。
Correct code below.正确的代码如下。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.