React Router with Redux:仅将必要的道具传递给 child 级路由
React Router with Redux: Pass only necessary props down to child level routes
我有一个连接到 redux 商店的 App 组件:
import React from 'react'
import { connect } from 'react-redux'
function App(props) {
return (
<div>
{props.children}
</div>
);
}
function mapStateToProps(state) {
return {
todos: state.something
}
}
export default connect(mapStateToProps)(App)
App 是我的 React 路由器层次结构中的根级组件,因此接收所有 child 路由作为 children:
export default(
<Route component={App} path="/">
<IndexRoute component={Home} />
<Route component={PageNotFound} path="*" />
</Route>
);
我希望能够将通过 mapStateToProps
传递给 App
的道具传递给 child 组件。似乎接受的方法是使用 cloneElement
允许将道具传递给 children ()。所以上面第一个片段中的代码:
<div>
{props.children}
</div>
变成:
<div>
{React.cloneElement(props.children, { ...props }
</div>
我觉得这很丑陋,因为这意味着我盲目地将所有道具从我连接的应用程序组件传递到我的 children 路由组件。
这真的是公认的做法吗?
如果您知道 mapStateToProps
中创建了哪些道具,您可以仅提取并进一步传递它们。
此外,如果您 return 具有来自 mapStateToProps
的所有必要数据的单个道具,我们将其命名为 componentState
:
可能会有所帮助
function mapStateToProps({todos, somethingElse}) {
return {
componentState: { todos, somethingElse }
}
}
那以后就只能传这一个prop了
<div>
{React.cloneElement(props.children, { componentState: this.props.componentState }
</div>
我有一个连接到 redux 商店的 App 组件:
import React from 'react'
import { connect } from 'react-redux'
function App(props) {
return (
<div>
{props.children}
</div>
);
}
function mapStateToProps(state) {
return {
todos: state.something
}
}
export default connect(mapStateToProps)(App)
App 是我的 React 路由器层次结构中的根级组件,因此接收所有 child 路由作为 children:
export default(
<Route component={App} path="/">
<IndexRoute component={Home} />
<Route component={PageNotFound} path="*" />
</Route>
);
我希望能够将通过 mapStateToProps
传递给 App
的道具传递给 child 组件。似乎接受的方法是使用 cloneElement
允许将道具传递给 children (
<div>
{props.children}
</div>
变成:
<div>
{React.cloneElement(props.children, { ...props }
</div>
我觉得这很丑陋,因为这意味着我盲目地将所有道具从我连接的应用程序组件传递到我的 children 路由组件。
这真的是公认的做法吗?
如果您知道 mapStateToProps
中创建了哪些道具,您可以仅提取并进一步传递它们。
此外,如果您 return 具有来自 mapStateToProps
的所有必要数据的单个道具,我们将其命名为 componentState
:
function mapStateToProps({todos, somethingElse}) {
return {
componentState: { todos, somethingElse }
}
}
那以后就只能传这一个prop了
<div>
{React.cloneElement(props.children, { componentState: this.props.componentState }
</div>