迁移到 react-router v4 - 使用 children 路由需要路由器道具

Migrating to react-router v4 - Route with children which requires router props

我能得到一些关于如何使用我的 AppMain 组件的建议吗,该组件使用从 react-router 传下来的道具来获取数据。

这是我到目前为止所做的更改

v3:

<Router history={browserHistory} >
  <Route component={AppMain} exact path="/" >
    <IndexRoute name="Home" component={Home} />
    <Route name="Site Details" path="/details" component={SiteDetails} />
    <Route name="Home" component={Home} path="*" />
  </Route>
</Router>

v4

  <Router>
        <div>
          {/*<AppMain>*/}
          <Route component={AppMain} >
            <main>
              <Grid fluid className={classnames('app-content', { 'expanded': !this.state.mobileView && this.state.open })}>
                <Switch>
                  <Route name="Home" exact path="/" component={Home} />
                  <Route name="Site Details" exact path="/details" component={SiteDetails} />
                </Switch>
              </Grid>
            </main>
          </Route>
          {/*</AppMain>*/}
        </div>
  </Router>

如您所见,我尝试了多种方法同时显示AppMainHome/SiteDetails。这种方法给了我这个警告,它显示 AppMain 但它的 children 的 none:

You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

另一种使用 <AppMain> 的方法没有传递 props.location.state...,我正在尝试将我的 AppMain 代码转换到此处:

v3

if (props.params.division !== undefined) {
  this.getDivision(props.params.division);
} else {
  this.getDivisions();
}

v4

if (props.location.state !== undefined) {
  if (props.location.state.division !== undefined) {
    this.getDivision(props.location.state.division.code);
  } else {
    this.getDivisions();
  }
} else {
  this.getDivisions();
}

如果:

React 路由器 v4:

     <Router>
        <div>
          <AppMain>
            <main>
              <Grid fluid className={classnames('app-content', { 'expanded': !this.state.mobileView && this.state.open })}>
                <Switch>
                  <Route name="Home" exact path="/" component={Home} />
                  <Route name="Site Details" exact path="/details" component={SiteDetails} />
                </Switch>
              </Grid>
            </main>
          </AppMain>
        </div>
     </Router>

如果您需要在 AppMain 中使用位置道具,只需将其用 withRouter 组件包裹即可:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

原来我需要做的就是在 Switch 之外添加一个 RouteAppMain,没有路径。

这是我的解决方法:

  <Router>
        <div>
          <Route component={AppMain} />
            <main>
              <Grid fluid className={classnames('app-content', { 'expanded': !this.state.mobileView && this.state.open })}>
                <Switch>
                  <Route name="Site Details" exact path="/details" component={SiteDetails} />
                  <Route name="Home" component={Home} />
                </Switch>
              </Grid>
            </main>
        </div>
  </Router>