【问题标题】:How to create redirect rules in React without redirecting to same route?如何在 React 中创建重定向规则而不重定向到相同的路由?
【发布时间】:2019-01-17 00:21:00
【问题描述】:

我有一个名为 AuthenticatedRoute.tsx 的文件,在我的 Router.tsx 文件中用作我所有受保护/经过身份验证的路由的模板。

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'} />;
    }
};

如果用户的个人资料不完整,上述所有尝试都是将用户重定向到不同的路线。

  1. 如果用户没有国家,请将他们重定向到选择国家页面。
  2. 如果用户没有电话号码,请将其重定向到添加电话号码页面。
  3. 如果用户的电话号码未经验证,请将其重定向到验证电话号码页面。
  4. 如果用户在上述任何路线上并且已经拥有该数据,请重定向到仪表板。
  5. 最后,如果没有满足任何规则,只需渲染他们试图获取的组件/路由。

这里出现的问题是,如果用户尝试前往所选国家或添加电话号码路由,则会出现控制台错误:

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.

当用户未完整填写个人资料时,如何解决重定向到这些路线的问题?

【问题讨论】:

  • path 实际上是当前路由吗,如果是,它看起来像您要比较的字符串吗?
  • @MatthewHerbst - 是的,path 是当前路线。我可以通过在getRender 函数顶部记录它来确认。

标签: javascript reactjs typescript react-router


【解决方案1】:

路径检查不起作用的原因似乎是重定向到仪表板。用户被重定向到选择国家,然后检查没有返回并继续检查去仪表板,这导致检查国家,这导致去选择国家,等等。

我们可以这样改写:

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;
};

【讨论】:

    猜你喜欢
    • 2016-12-20
    • 2021-07-22
    • 2020-05-24
    • 2016-12-15
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多