简体   繁体   English

你如何将支柱传递到所有反应路线? (动态更改标题)

[英]How do you pass a prop to all react routes? (Change title dynamically)

I am using redux to manage state, so I'm passing state and bound actions from the root component. 我使用redux来管理状态,所以我从根组件传递状态和绑定的动作。

I am using react-router-redux 's ConnectedRouter , with a switch inside containing all my routes and redirects. 我正在使用react-router-reduxConnectedRouter ,里面有一个包含所有路由和重定向的交换机。 And I'm trying to prevent passing a setRouteTitle along with the routeTitle . 我试图阻止传递setRouteTitlerouteTitle The router switch is similar to the code below. 路由器开关类似于下面的代码。

<Switch>
  <Route
      exact 
      path="/" 
      component={ Dashboard }
      routeTitle="Dashboard"
      setRouteTitle={ setRouteTitle }
      dashboardState={ state.dashboard }/>

  <Route
      exact 
      path="/gear" 
      component={ Gear }
      routeTitle="Gear Management"
      setRouteTitle={ setRouteTitle }
      gearState={ state.gear }/>

  <Route
      exact 
      path="/users" 
      component={ Users }
      routeTitle="Users Management"
      setRouteTitle={ setRouteTitle }
      usersState={ state.users }/>
</Switch>

It just seems redundant to first pass a function and its parameter for the component to run as soon as it will mount/has props, then second defining it on every single route. 首先传递一个函数及其参数使组件运行,只要它将挂载/具有道具,然后第二次在每个路由上定义它,这似乎是多余的。

Any way to do this without creating a new component that extends Route or something, or would this be a good idea? 没有创建一个扩展Route或其他东西的新组件的任何方法,或者这是一个好主意?

Perhaps you can create a wrapper component for Route 也许你可以为Route创建一个包装器组件

// make sure 'setRouteTitle' is in the scope of MyRoute
// and routeProps has the structure = { component, routeTitle, ...etc  }
function MyRoute ({ ...routeProps }) => (
  <Route
    exact 
    path="/" 
    setRouteTitle={setRouteTitle}
    {...routeProps}
  />
);

So that your switch component would be more succinct, like the following: 这样你的开关组件就会更加简洁,如下所示:

// in js 
const setRouteTitle = /* some value */
const dashboardProps = { component: Dashboard, routeTitle: 'Dashboard', dashboardState: state.dashboard } 
const gearManagementProps = { component: Gear, /* ... the rest of props */ }
const userProps = { component: User, /* ... the rest of props */ }

// jsx in your render
<Switch>
  <MyRoute {...dashboardProps} />
  <MyRoute {...gearManagementProps} />
  <MyRoute {...userProps} />
</Switch>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM