反应嵌套路线没有改变

时间:2018-12-15 21:21:13

标签: reactjs react-native react-redux react-router

我正在尝试在仪表板内部创建一些路由,但由于存在一些缺陷,我的项目有一个根页,其中包含/ admin s working fine, inside of the admin page Im using the same code with /home but it无效的路由(访问/ admin / home)。那是我的代码:

根:

render() {
    return (
      <Router>
        <div>
        <Navigation authUser={this.state.authUser} />

          <Route
            exact path={routes.ADMIN}
            component={AdminPage}
          />
        </div>
      </Route>

管理员:      render(){     const {users} = this.props;

return (
  <div>
    <Switch>
      <Route
        exact path={routes.ADMIN_HOME}
        component={AdmHomePage}
      />

    </Switch>

  </div>

route.ADMIN_HOME =='/ home'

route.ADMIN =='/ admin'

1 个答案:

答案 0 :(得分:0)

您需要为子路由(包括父路径)嵌套整个路径。

例如route.ADMIN_HOME应该为/admin/home

同样重要的是,父路线不包括确切的道具。这是因为除非精确地/admin,否则父路径不会渲染,因此它将永远不会在父组件中渲染路径。

我在下面附上了一个可运行的示例。注意;我已经将BrowserRouter切换为HashRouter,以便它可以在StackOverflow上运行。

const HashRouter = ReactRouterDOM.HashRouter;
const Route = ReactRouterDOM.Route;
const Link = ReactRouterDOM.Link;
const Switch = ReactRouterDOM.Switch;

const Players = () => (
  <div>
    <h5>Players</h5>
    <Switch>
      <Route path="/players/joe" render={() => <div>Joe</div>} />
      <Route path="/players/emily" render={() => <div>Emily</div>} />
    </Switch>
  </div>
);

ReactDOM.render(
  <HashRouter>
    <div>
      <h5>Navigation</h5>
      <ul>
        <li><Link to="/players">Players</Link></li>
        <li><Link to="/players/joe">Players - Joe</Link></li>
        <li><Link to="/players/emily">Players - Emily</Link></li>
        <li><Link to="/about">About</Link></li>
      </ul>
      <Switch>
        <Route path="/players" component={Players} />
        <Route path="/about" render={() => <div>About Page</div>} />
      </Switch>
    </div>
  </HashRouter>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<div id="root"></div>