![](/img/trans.png)
[英]Can't perform a React state update on an unmounted component with useEffect hook
[英]can't perform a react state update on an unmounted component issue with useEffect
我正在尝试将我的用户重定向到私有路由。 我正在使用 redux thunk 从数据库中获取用户信息,使用 storeUser(),如果信息存在,则用户继续,否则他们将被重定向回主页。 然而,它没有按预期工作。 当它应该继续时,它重定向回主页。 我可以使用基于类的语法和 componentDidMount 来做到这一点。 我试图通过使用 authChecked 状态来确定组件何时完成渲染来解决无法访问 componentDidMount 的问题
const PrivateRoute = (props) => {
const [authChecked, handleAuthChecked] = useState(false);
const [isAuth, handleIsAuth] = useState(false);
useEffect(() => {
props
.storeUser()
.then(() => {
props.user.email ? handleIsAuth(true) : handleIsAuth(false);
handleAuthChecked(true);
})
.catch(() => {
handleAuthChecked(true);
});
}, [props]);
if (authChecked) {
return isAuth ? <props.component /> : <Redirect to="/" />;
}
return null;
};
const mapStateToProps = (state) => {
return {
user: state.user,
};
};
export default connect(mapStateToProps, { storeUser })(PrivateRoute);
代码将始终重定向用户。 即使 props.user.email 为 true,isAuth 也永远不会返回 true。 它在有机会运行 handleIsAuth(true) 之前运行并重定向
您有 2 个可能导致您看到的缺陷的问题:
useEffect
的函数作用域和您对storeUser
的回调引起的。 不要依赖回调来确定用户是否有电子邮件地址,只需在您的渲染条件中执行此操作,然后让 redux + react 渲染周期帮助您。storeUser
操作。 并非每次props
更新。例如:
const PrivateRoute = (props) => {
const [authChecked, handleAuthChecked] = useState(false);
useEffect(() => {
props
.storeUser()
.then(() => {
handleAuthChecked(true);
})
.catch(() => {
handleAuthChecked(true);
});
}, []);
if (authChecked) {
return !!props.user.email
? <props.component />
: <Redirect to="/" />;
}
return null;
};
const mapStateToProps = (state) => {
return {
user: state.user,
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.