javascript - 如何正确使用 React 路由器重定向?

标签 javascript reactjs redirect redux react-router

我遇到了一个问题。 当我想做重定向时,我收到此错误
您尝试重定向到当前所在的同一路线:“/”
我的 App.js 文件如下所示

render() {
    const { auth } = this.props;
    if (!auth.isAuthentificated) {
      return <Redirect to="/" />;
    }
      
    return (
      ...
      <Switch>
        <Route path="/welcome" component={Welcome} />
        <Route path="/user-info" component={UserInfo} />
        <Route path="/" component={LoginPage} />
      </Switch>
    );
  }

如果我的代码对您来说不清楚 - 请帮助我提供任何建议。如果 !auth.isAuthentificated === true,我如何将用户从任何路由重定向到 LoginPage 组件
我正在使用 react-router 4.2.0,

最佳答案

在重定向到该路径之前,您需要验证您是否已经位于该路径:

import {withRouter} from 'react-router-dom';

// ...

render() {
    const { auth } = this.props;
    const {pathname} = this.props.location;

    if (!auth.isAuthentificated && pathName !== '/') {
        return <Redirect to="/" />;
    }

    return (
        ...
        <Switch>
            <Route path="/welcome" component={Welcome} />
            <Route path="/user-info" component={UserInfo} />
            <Route path="/" component={LoginPage} />
        </Switch>
    );
}

关于javascript - 如何正确使用 React 路由器重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50164758/

相关文章:

javascript - Google map - 默认图钉仍然显示并遮盖自定义图标

php - 在表达式引擎2.2.2中;我的 css 不能在所有地方都工作,为什么?

reactjs - Babel 未知选项 : . 调用者

javascript - 如果页面上的所有图像都返回错误重定向?

redirect - 301 重定向到 github 托管的网站?

javascript - 尝试创建一个 future 的日期而不是创建一个过去的日期

javascript - 打开和关闭模态窗口不起作用

reactjs - 如何禁用 ReactJs 的 laravel 路由

css - 有条件地覆盖 CSS 中的 AntD Select 样式

servlets - 重定向到另一个网址