2016-09-20 55 views
0

我有一个连接到终极版商店的应用程序组件:阵营路由器与终极版:通过只需要道具到孩子级别路线

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) 

应用程序是在我的反应路由器层次等的根级组件接收所有子路由儿童:

export default(
    <Route component={App} path="/"> 
    <IndexRoute component={Home} /> 
    <Route component={PageNotFound} path="*" /> 
    </Route> 
); 

我希望能够通过,在对App通过mapStateToProps传递给子组件的道具。看起来可以接受的方式是使用cloneElement来将道具传递给儿童(How to pass props to {this.props.children})。因此在上面的第一个片段的代码:

<div> 
    {props.children} 
</div> 

变为:

<div> 
    {React.cloneElement(props.children, { ...props } 
</div> 

我觉得这个比较难看,因为这意味着我盲目地传球从连接的应用程序组件的所有道具给我的孩子航线组件。

这真的是这样做的接受方式吗?

+0

我想知道如果也许这是一个使用的方法? http://stackoverflow.com/questions/36730619/unable-to-pass-redux-store-beyond-react-router/39300618#39300618 –

+1

如果你不希望所有的道具“盲目地”传下来,你可以连接''你的'Home'或者其他组件,比如你使用'App'组件,并且每个组件都有一个不同的'mapStateToProps'函数。 –

+0

@MarioTacke谢谢。说得通。 –

回答

2

如果您知道在mapStateToProps中创建了哪些道具,则可以仅提取并传递更多道具。

此外,它可能会有所帮助,如果你返回一个道具与mapStateToProps所有必要的数据,让我们将其命名为componentState

function mapStateToProps({todos, somethingElse}) { 
    return { 
    componentState: { todos, somethingElse } 
    } 
} 

后来的后来,你可以只传递这个单一支柱下来

<div> 
    {React.cloneElement(props.children, { componentState: this.props.componentState } 
</div> 
+0

是的,这是一个很好的方法。结束时,每个路由组件都是一个具有mapStateToProps的连接容器。 –