javascript - 如何在状态更改后停止 useEffect 运行?
问题描述
这里的问题是,当用户注销时,isAuthed
变成null
(如预期的那样)并且触发useEffect()
,然后isAuthed
变成false
. 正因为如此,当用户登录时,登录是成功的,但是isAuthed
已经成功了,false
所以不会调用私有路由。我该如何解决这个问题?
状态由 Redux 处理。isAuthed
的初始值为null
。
提前谢谢你的帮助。
function App() {
return (
<Provider store={store}>
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<PublicRoute path="/login" component={Login} />
<PrivateRoute path="/dashboard" component={Dashboard} />
function PrivateRoute({ component: Component, isAuthed, ...rest }) {
async function verifyUser() {
const res = await fetch(,); // call users/me endpoint
if (res.status === 200) {
// dispatch action to change `isAuthed` to `true`
} else {
// dispatch action to change `isAuthed` to `false`
};
};
useEffect(() => {
if (isAuthed === null) {
verifyUser();
}
}, [isAuthed]);
return (
<Route
{...rest}
render={(props) => isAuthed == null ? "loading" :
isAuthed == true ? <Component {...props} /> : <Redirect to={{ pathname: '/', state: { from: props.location } }} />}
/>
);
};
function PublicRoute({ component: Component, isAuthed, ...rest }) {
return (
<Route
{...rest}
render={(props) => isAuthed == false || isAuthed == null ? <Component {...props} /> : <Redirect to={{ pathname: '/' }} />}
/>
)
};
const handleLogin = async (event) => {
event.preventDefault();
const res = await fetch(,); // call login endpoint to check user credentials
if (res.status === 200) {
props.history.push('/dashboard');
} else {}
解决方案
推荐阅读
- jupyter-lab - 如何在 Jupyter Labs 中显示 OpenCV VideoCapture
- angular - 我无法根据 Angular 中的键来迭代嵌套对象
- sql - AS400 DB2 SQL-0181 日期、时间或时间戳中的值无效
- c++ - Boost asio ssl socket 不接收完整数据 tcp socket 和 ssl socket 的不同行为
- android - 如何让资产超过 AppBar?
- c++ - SFML 不在另一个线程中轮询事件
- c# - 无法连接到调试器可可应用程序 Visual Studio MAC
- javascript - 为什么不调用“if (member)”?
- reactjs - 反应原生轮播
- c++ - 管线创建后更新 VkGraphicsPipelineCreateInfo 会影响当前渲染场景吗?