我需要在 useEffect 检查用户是否具有所需角色后渲染组件,但它总是重定向我,因为它首先执行渲染函数,然后执行 useEffect
这是我的代码:
import { Route, Redirect } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { checkIfUserHasRequiredRole } from '../../utility/utility';
import PathConst from '../../utils/PathConst';
const AuthRoute = ({
Component, path, exact = false, isAuthenticated, requiredRoles,
}) => {
const [userHasRequiredRole, setUserHasRequiredRole] = useState(false);
const roles = useSelector((state) => state.role.roles);
const isAuthed = isAuthenticated;
useEffect(() => {
if (roles) {
const userRole = checkIfUserHasRequiredRole(requiredRoles, roles);
setUserHasRequiredRole(userRole);
}
}, [roles]);
return (
<Route
exact={exact}
path={path}
render={() => (
isAuthed && userHasRequiredRole ? (<Component />)
: (
<Redirect
to={PathConst.toLoginPage}
/>
))}
/>
);
};
export default AuthRoute;
函数'checkIfUserHasRequiredRole' 返回真,但'useHasRequiredRole' 在触发if 语句时仍然为假。我还尝试使用没有依赖项的相同 useEffect 函数。 我该如何管理?
答案 0 :(得分:1)
您可以进行设置,但这需要额外的渲染,以便 userHasRequiredRole
更新并生效。
既然您可以根据 roles
确定您需要什么,那么您可以,
import { useHistory } from "react-router-dom";
const history = useHistory();
useEffect(() => {
if (roles) {
const userRole = checkIfUserHasRequiredRole(requiredRoles, roles);
if (this role is not good) {
history.push(PathConst.toLoginPage)
}
}
}, [roles])