我正在使用 redux 来管理状态,因此我从根组件传递状态和绑定(bind)操作。
我正在使用 react-router-redux
的 ConnectedRouter
,里面有一个开关包含我所有的路由和重定向。我正试图阻止将 setRouteTitle
与 routeTitle
一起传递。路由器开关类似于下面的代码。
<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>
首先传递一个函数及其参数,让组件在挂载/拥有 props 后立即运行,然后在每条路由上定义它,这似乎是多余的。
有什么方法可以在不创建扩展 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}
/>
);
这样你的 switch 组件会更简洁,像下面这样:
// 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>
关于javascript - 你如何将 Prop 传递给所有反应路线? (动态更改标题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45227833/