React Router v4 - 嵌套路由问题

时间:2017-07-17 23:11:41

标签: javascript reactjs react-router react-router-v4

我有以下App组件。

class App extends React.Component {
  constructor() {
    super();
    this.state = {}
  }

  // various methods that interact with state defined here

  render() {
    const Main = () => (
      <div className="main-wrapper">
        <ListPicker/>
        <ListPane/>
      </div>
    );

    const Search = () => (
      <div className="search-wrapper">
        <ul className="search-results">
          <li>Search Results</li>
        </ul>
      </div>
    );

    return (
        <div className="app-wrapper">
          <Title/>
          <SearchBar listResults={this.listResults}/>

          <Route exact path="/" component={Main}/>
          <Route path="/search" component={Search}/>
        </div>
    )
  }
}

index.js中呈现的内容:

import React from 'react';
import { render } from 'react-dom';
import { 
  BrowserRouter as Router,
  Route
} from 'react-router-dom';

import App from './components/App';

const Root = () => {
  return (
    <Router>
      <div>
        <Route exact path="/" component={App}/>
      </div>
    </Router>
  )
};

render(<Root/>, document.getElementById('root'));

App的底部,您可以看到我试图让Main组件或Search组件呈现在<Title/>和{{1}之下}基于路径<SearchBar/>/。据我所知,从React-Router文档来看,我正在做他们的示例应用程序中显示的内容,但我无法正常工作。使用此当前设置/searchMain处呈现正常,但导航到/时,/search内无任何渲染。我还尝试在<Root/>中包装这两个<Routes/>但得到相同的结果。我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

您在index.js中添加了exact Route。所以路线/search无法找到方法。所以改为:

const Root = () => {
  return (
    <Router>
      <div>
        <Route path="/" component={App}/>
      </div>
    </Router>
  )
};