我正在尝试在每次路线更改时对用户进行身份验证react-router-dom
and react hooks
。
这个想法是,每次用户导航到某个路线时,系统都会进行 api 调用并对用户进行身份验证。
我需要实现这一目标,因为我使用react-redux
,并且在每个窗口重新加载时,redux 状态不会持久。所以我需要设置isLoggedNow
支撑true
again:
const PrivateRoute = ({
component: Component,
checkOnEachRoute: checkReq,
isUserLogged,
...rest
}) => {
const [isLoggedNow, setLogged] = useState(isUserLogged);
useEffect(
() => {
const fetchStatus = async () => {
try {
await selectisUserLogged();
setLogged(true);
} catch (error) {
console.log(error);
}
};
fetchStatus();
},
[isUserLogged],
);
return (
<Route
{...rest}
render={props =>
isLoggedNow ? (
<div>
<Component {...props} />
</div>
) : (
<Redirect
to={{
pathname: '/login',
}}
/>
)
}
/>
);
};
然后我会使用上面的PrivateRoute
像这样:
function App(props) {
return (
<div>
<Switch location={props.location}>
<Route exact path="/login" component={Login} />
<PrivateRoute exact path="/sidebar" component={Sidebar} />
</Switch>
</div>
);
}
首先是isUserLogged
is true
,但是在窗口重新加载后我收到错误Warning: Can't perform a React state update on an unmounted component.
那么我怎样才能实现这一点,以便在每个窗口重新加载时我对用户进行身份验证?我正在寻找某种componentWillMount
.
像这样的东西有效(其中isUserLogged
是 redux 的一个 prop):
function PrivateRoute({ component: Component, isUserLogged, ...rest }) {
const [isLoading, setLoading] = useState(true);
const [isAuthenticated, setAuth] = useState(false);
useEffect(() => {
const fetchLogged = async () => {
try {
setLoading(true);
const url = new URL(fetchUrl);
const fetchedUrl = await fetchApi(url);
setAuth(fetchedUrl.body.isAllowed);
setLoading(false);
} catch (error) {
setLoading(false);
}
};
fetchLogged();
}, []);
return (
<Route
{...rest}
render={props =>
// eslint-disable-next-line no-nested-ternary
isUserLogged || isAuthenticated ? (
<Component {...props} />
) : isLoading ? (
<Spin size="large" />
) : (
<Redirect
to={{
pathname: '/login',
}}
/>
)
}
/>
);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)