首页 > 解决方案 > 如何正确使用 React 路由器重定向?

问题描述

我遇到了一个问题。当我想做重定向时收到此错误 我的App.js文件如下所示
You tried to redirect to the same route you're currently on: "/"

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

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

标签: javascriptreactjsredirectreduxreact-router

解决方案


在重定向到该路径之前,您需要验证您尚未位于该路径:

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

推荐阅读