首页 > 解决方案 > 将数据传递给反应中的所有嵌套路由

问题描述

我在我的项目中使用嵌套路由。
注意:我正在使用 redux 进行状态管理。

<Provider store={store}>
  <PersistGate persistor={persistor}> 
    <BrowserRouter>
      <ToastContainer hideProgressBar={true} />
      <Switch>      
        <Route path="/" exact component={Home} />
        <Route path='/login'exact component={Login} />
        <Route path='/signup'exact component={Signup} />
        <Route path="/room/*" component={Roomroute} />
        <Route path="/createroom" component={Createroom} />
      </Switch>
    </BrowserRouter>
  </PersistGate>
</Provider>
function Roomroute() {
  return(
    <div>
      <Switch>
        <Route path="/room/stream" exact component={Stream} />    
        <Route path="/room/work" exact component={Classwork} /> 
        <Route path="/room/people" exact component={People} />   
        <Route path="/room/work/:id" exact component={Workview} />   
      </Switch>
    </div>
  )
}
() => history.push({
  pathname:"/room/stream",
  state: {
    roomdata:roomdata
  }        
})

我想在 roomRoute() 中的所有嵌套路由中使用通过历史发送的房间数据。告诉我如何在 roomRoute 中获取数据以及如何在 roomRoute 中的所有路由(组件)中使用它

标签: javascriptreactjsreact-routerreact-router-dom

解决方案


零件:

class Component extends React.Component {
  render() {
    const {text, match: {params}} = this.props;

    const {name} = params;

    return (
        <p>
          {text} {name}
        </p>
      
    );
  }
}

用法:

<Route path="/path/:name" render={(props) => <Component text="Hello, " {...props} />} />

您必须重新生成此模型才能将道具传递给子组件。


推荐阅读