如何使用React Router v4在root / home视图中添加嵌套路由?

时间:2017-04-18 10:27:40

标签: react-router

遵循此说明:https://reacttraining.com/react-router/web/example/basic

简单地说,我希望将所有嵌套视图主题移至主页

如您所见,主题菜单具有嵌套视图,嵌套视图通过匹配路径解析,如\topics\rendering\topics\components等。 但是在我的情况下,我想将所有嵌套视图放入主菜单,因为主菜单是根路径/,所以它似乎不再起作用了。

以下是我的预期,

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/topics">Topics</Link></li>
      </ul>

      <hr/>

      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/topics" component={Topics}/>
    </div>
  </Router>
)

const Home = ({ match }) => (
  <div>
    <h2>Home</h2>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>
          Rendering with React
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>
          Components
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>
          Props v. State
        </Link>
      </li>
    </ul>

    <Route path={`${match.url}/:desc`} component={SubHome}/>
    <Route exact path={match.url} render={() => (
      <h3>Please select.</h3>
    )}/>
  </div>
)

const SubHome = ({ match }) => (
  <div>
    <h3>{match.params.desc}</h3>
  </div>
)

但是这不起作用,我想这可能是因为家庭拥有根路径/

1 个答案:

答案 0 :(得分:0)

我无法为我的案例找到官方解决方案,所以我做了一个解决方法。

我为主页菜单提供了/home而非/的路径,并且由于应用最初会以/开头,因此我添加了重定向上面,简单的代码如下,

const BasicExample = () => (
  <Router>
    <div>
      <Redirect from="/" to="/home" /> 
      <ul>
        <li><Link to="/home">Home</Link></li> 
        <li><Link to="/about">About</Link></li>
        <li><Link to="/topics">Topics</Link></li>
      </ul>

      <hr/>

      <Route exact path="/home" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/topics" component={Topics}/>
    </div>
  </Router>
)

const Home = ({ match }) => (
  <div>
    <h2>Home</h2>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>
          Rendering with React
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>
          Components
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>
          Props v. State
        </Link>
      </li>
    </ul>

    <Route path={`${match.url}/:desc`} component={SubHome}/>
    <Route exact path={match.url} render={() => (
      <h3>Please select.</h3>
    )}/>
  </div>
)

const SubHome = ({ match }) => (
  <div>
    <h3>{match.params.desc}</h3>
  </div>
)