首页 > 解决方案 > '你试图重定向到你当前所在的同一条路线:“/”'当使用带有状态的重定向组件时

问题描述

我正在尝试创建一个包含两个页面的小型演示应用程序,one并且two. 用户可以通过按下按钮从一个页面导航one到另一个页面,但前提是第二个页面中的位置对象的状态包含一个属性。如果没有,则将用户重定向到.twokeyone

我遇到的问题是,当使用to 对象从重定向one和传递状态到时two,React Router 警告:

您尝试重定向到您当前所在的同一条路线:“/”

这对我来说没有意义,因为我试图将用户从/oneto 重定向到/two,而不是/to /two

应用程序.js

import React, { Component } from 'react';
import './App.css';

import { NavLink, Redirect, Route, BrowserRouter as Router, Switch } from 'react-router-dom';


const App = () => (
  <Router>
    <div className="App">
      <ul>
        <li>
          <NavLink to="/one">One</NavLink>
        </li>
        <li>
          <NavLink to="/two">Two</NavLink>
        </li>
      </ul>

      <Switch>
        <Route path="/one" component={One} />
        <Route path="/two" component={Two} />
      </Switch>
    </div>
  </Router>
);


class One extends Component {
  constructor(props) {
    super(props);

    this.state = {
      shouldRedirect: false,
    };

    this.redirect = this.redirect.bind(this);
  }

  redirect() {
    this.setState({
      shouldRedirect: true,
    });
  }

  render() {
    const { shouldRedirect } = this.state;

    if (shouldRedirect) {
      return (
        // Replacing the below Redirect with the following corrects the error,
        // but then I'm unable to pass state to the second page.

        // <Redirect to="/two" />

        <Redirect
          to={{
            pathName: '/two',
            state: {
              key: 'Some data.',
            },
          }}
        />
      );
    }

    return (
      <div>
        <h3>This is the first page.</h3>
        <button type="button" onClick={this.redirect}>Click me to go to page two.</button>
      </div>
    );
  }
}

class Two extends Component {
  constructor(props) {
    super(props);

    this.state = {
      shouldRedirect: false,
    };

    this.redirect = this.redirect.bind(this);
  }

  componentWillMount() {
    const { location } = this.props;

    if (location.state && location.state.key) {
      const { key } = location.state;
      this.key = key;
    } else {
      this.redirect();
    }
  }

  redirect() {
    this.setState({
      shouldRedirect: true,
    });
  }

  render() {
    const { shouldRedirect } = this.state;

    if (shouldRedirect) {
      return (
        <div>
          <p>You&apos;re being redirected to the first page because a key was not provided.</p>
          <Redirect to="/one" />
        </div>
      );
    }

    return (
      <div>
        <h3>This is the second page.</h3>
        <p>The key you provided was &quot;{this.key}&quot;.</p>
      </div>
    );
  }
}

export default App;

应用程序.css

.App {
  text-align: center;
}

标签: node.jsreactjsreact-routercreate-react-app

解决方案


您正在传递pathName而不是pathname. 这应该可以解决问题。代码沙箱
上的工作示例。

<Redirect
      to={{
        pathname: "/two",
        state: {
          key: "Some data."
        }
      }}
    />

推荐阅读