将路由器道具共享到未包含在路由器中的组件

问题描述 投票:0回答:1

我的路线看起来像这样:(Main.js)

<BrowserRouter>
    <Switch>
      <Route name="login" exact path="/login" component={LoginPass} />
      <Route name="loginWithTripId" exact path="/login/:tripid" component={LoginPass} />
      <PrivateRoute path="/trips/:tripid" component={App} />
    </Switch>
  </BrowserRouter>

在我的App渲染方法中:(App.js)

render() {
    const { classes, ...other } = this.props;
    return (
  <div className={classes.root}>
    <Appbar
    />

    <LeftDrawer
    />

    <Switch>
      <Route
        path={'/trips/dashboard'}
        render={props => (
          <Dashboard
            {...other}
            {...props}
          />
        )}
      />
      <Route
        path={'/trips/:tripid/itinerary'}
        render={props => (
          <Itinerary
            {...other}
            {...props}
          />
        )}
      />
      <Route render={() => <Redirect to={'/trips/dashboard'} />} />
    </Switch>
  </div>
);
}

如何共享在仪表板和行程中传递的路由器道具而不将其保存在App本地状态?我尝试在LeftDrawer和Appbar中使用withRouter,但它有其父(Main.js)的路由器道具。我得到match.path =“/ trip /:tripid”而不是“trip /:tripid / itinerary”或“trip / dashboard”。

对于上下文,我需要根据URL渲染appbar / leftdrawer组件中的某些元素,并且我想使用match.path道具传递到Itinerary和Dashboard Components来匹配。例如,如果我在路线'/ trip / dashboard'中,则会加载仪表板。所以appbar需要有一个ADD按钮来添加行程。行程视图中的appbar中不显示此按钮。在过去,我在Dashboard和Itinerary Components中有LeftDraewr和Appbar,但我将它上移了一级。

reactjs react-router
1个回答
1
投票

好吧,如果你想要AppBar中的路由器道具(在所有页面上呈现),那么你可以将它包装在匹配每个路径的路径中:

<Route path="*" component={AppBar}/>

使用'*'路径,它将像现在一样在每个页面上呈现,并且被包裹在<Route/>中,然后它应该有路由器道具可用。

© www.soinside.com 2019 - 2024. All rights reserved.