【发布时间】:2021-02-21 22:18:15
【问题描述】:
在反应中,我有一个私有路由组件,它有一个 isAuthenticated 状态值,用于渲染它正在包装的组件,或重定向回我的登录页面。
为了检测刷新并执行身份验证检查,我添加了一个useEffect 挂钩,希望我可以检查身份验证状态,然后更新isAuthenticated,然后返回组件或相应地重定向。
const PrivateRoute: React.FC<IPrivateRouteProps> = (props) => {
const dispatch = useDispatch();
const [isAuthenticated, setIsAuthenticated] = React.useState(false);
useEffect(() => {
authService.getIdentity().then(response => {
if (response) {
dispatch(signIn(new Identity(response.account)));
setIsAuthenticated(true);
} else {
setIsAuthenticated(false);
}
});
}, [])
return isAuthenticated ? (
<Route {...props} component={props.component} render={undefined} />
) : (
<Redirect to={{ pathname: props.redirectPath }} />
);
};
很遗憾,这不起作用,我不确定为什么或如何解决它。
isAuthenticated 的值在渲染时始终为 false,我在控制台中收到以下错误......
index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
in PrivateRoute (at App.tsx:23)
我可以确认它确实流向了setIsAuthenticated(true),但这在渲染之前从未反映在isAuthenticated 的值中。
我该如何/应该如何解决这个问题?
谢谢,
【问题讨论】:
标签: reactjs react-hooks