我有一个名为 AuthenticatedRoute.tsx
的文件,在我的 Router.tsx
文件中用作所有 protected /经过身份验证的路由的模板。
export default ({ component: C, authUser: A, path: P, exact: E }:
{ component, authUser, path, exact }) => (
<Route
exact={E}
path={P}
render={props =>
getRender(A, P, props, C)
}
/>
);
getRender
函数运行以下内容:
const getRender = (user, path, props, C) => {
if (user) {
if (!user.country) {
return <Redirect to={'/select-country'} />;
} else if (!user.phoneNumber) {
return <Redirect to={'/add-phone'} />;
} else if (!user.phoneNumberVerified) {
return <Redirect to={'/verify-phone'} />;
} else if (path === '/select-country' || path === '/add-phone' || path === '/verify-phone') {
return <Redirect to={'/dashboard'} />;
} else {
return <C {...props} authUser={user} />;
}
} else {
return <Redirect to={'/signin'} />;
}
};
以上所有内容都试图在用户的个人资料不完整的情况下将用户重定向到不同的路线。
- 如果用户没有国家/地区,请将其重定向到选择国家/地区页面。
- 如果用户没有电话号码,请将其重定向到添加电话号码页面。
- 如果用户的电话号码未经过验证,请将其重定向到验证电话号码页面。
- 如果用户位于上述任何路线并且已有该数据,请重定向至信息中心。
- 最后,如果不满足任何规则,则仅渲染它们尝试获取的组件/路由。
此处出现的问题是,如果用户尝试前往所选国家/地区或添加电话号码路由,则会出现控制台错误:
Warning: You tried to redirect to the same route you're currently on: "/select-country"
我尝试添加更多逻辑,如下所示:
if (!user.country && path !== '/select-country') {
return <Redirect to={'/select-country'} />;
}
尽管我发生了无限重定向:
Error: Maximum update depth exceeded.
当用户未完整填写其个人资料时,如何解决重定向到这些路由的问题?
最佳答案
路径检查不起作用的原因似乎是重定向到仪表板。用户被重定向到选择的国家/地区,然后对该国家/地区的检查不会返回,并继续进行前往仪表板的检查,这会导致检查国家/地区,从而导致选择国家/地区,等等。
我们可以这样重写:
const getRender = (user, path, props, C) => {
const currentPage = <C {...props} authUser={user} />;
if(!user) {
return path === '/select-country' ? currentPage : <Redirect to={'/signin'} />;
}
if (!user.country) {
return path === '/select-country' ? currentPage : <Redirect to={'/select-country'} />;
}
if (!user.phoneNumber) {
return path === '/add-phone' ? currentPage : <Redirect to={'/add-phone'} />;
}
if (!user.phoneNumberVerified) {
return path === '/verify-phone' ? currentPage : <Redirect to={'/verify-phone'} />;
}
if (path === '/select-country' || path === '/add-phone' || path === '/verify-phone') {
return <Redirect to={'/dashboard'} />;
}
return currentPage;
};
关于javascript - 如何在 React 中创建重定向规则而不重定向到同一路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54227336/