如何在React JS中识别嵌套路由?

时间:2019-07-26 20:00:41

标签: reactjs react-router

我正在尝试使用react-router-dom在我的应用程序中定义嵌套路由。这是我的问题:问题是除App.js中定义的路由外,所有路由都工作正常。要使所有路线正常工作需要做什么?

index.js

ReactDOM.render(
  <Router>
    <Switch>
      <Route exact path="/app" component={App} />
      <Route path="/smartphones" component={() => <SmartphoneTable smartphones={PHONES} />} />
      <Route path="/sign-up" component={SignUpForm} />
      <Route component={() => <h1>Not found</h1>} />
    </Switch>
  </Router>,
  document.getElementById('root')
);

App.js

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      welcome: "you!"
    };
  }

  render() {
    const { match } = this.props;

    return (
      <Container>
        <Jumbotron>
          <h1>Hello, {this.props.name}, {this.props.age} y.o.!</h1>
          <p>{this.state.welcome}</p>
          <Switch>
            <Route path="/app/clock" component={() => <Clock interval="2000" />} />
            <Route path="/app/button" component={() => <ClickButton class="off" label="Press me" />} />
          </Switch>
        </Jumbotron>
      </Container>
    );

1 个答案:

答案 0 :(得分:2)

index.js中删除exact道具:

<Route path="/app" component={App} />

每次path更改为/app/foo时,都会卸载应用程序,因此会卸载子项。