为什么react-router将以前的路由与新的路由结合在一起?

时间:2018-08-22 11:50:30

标签: javascript reactjs navigation react-router

这是我的Router.js文件

// imports here

export default () => (
  <Router>
    <App>
      <Route exact path="/" component={Home} />
      <Route exact path="/users" component={Users} />
      <Route path="/users/:id" component={User} />
      <Route path="/about" component={About} />
    </App>
  </Router>
);

和我的App.js文件

const App = props => (
  <div>
    <nav>
      <Link to="/">Home</Link>
      <Link to={{ pathname: '/users', state: { prevPath: props.location.pathname } }}>Users</Link>
      <Link to="about">About</Link>
    </nav>
    {props.children}
  </div>
);

export default compose(withRouter)(App);

当我选择'/ users'路径,然后单击任何用户以导航到'/ users /:id'时,它工作正常,路由为http://localhost:3000/users/some-user-id。但是当我想在这条路线后导航到路线“ / about”

URL地址变成http://localhost:3000/users/about而不是http://localhost:3000/about吗?我在做什么错了?

2 个答案:

答案 0 :(得分:0)

在链接中使用反斜杠:

const App = props => (
  <div>
    <nav>
      <Link to="/">Home</Link>
      <Link to={{ pathname: '/users', state: { prevPath: props.location.pathname } }}>Users</Link>
      <Link to="/about">About</Link>
    </nav>
    {props.children}
  </div>
);

答案 1 :(得分:0)

在关于页面的链接中添加确切

    export default () => (
      <Router>
        <App>
          <Route exact path="/" component={Home} />
          <Route exact path="/users" component={Users} />
          <Route path="/users/:id" component={User} />
          <Route exact path="/about" component={About} />
        </App>
      </Router>
    );

并在App.js中添加反斜杠并破坏道具

const App = ({children, location}) => (
  <div>
    <nav>
      <Link to="/">Home</Link>
      <Link to={{ pathname: '/users', state: { prevPath: location.pathname } }}>Users</Link>
      <Link to="/about">About</Link>
    </nav>

    {children}
  </div>
);

export default compose(withRouter)(App);