简体   繁体   English

使用Redux的React Router:仅将必要的道具传递到子级路由

[英]React Router with Redux: Pass only necessary props down to child level routes

I have an App component that is connected to a redux store: 我有一个连接到Redux存储的应用程序组件:

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 is the root level component in my react router hierarchy and so receives all child routes as children: 应用是我的反应路由器层次结构中的根级组件,因此接收所有子路由作为子路由:

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

I want to be able to pass the props that are passed in to App via mapStateToProps to child components. 我希望能够将通过mapStateToProps传递到App的道具传递给子组件。 It seems the accepted way to do this is to use cloneElement to allow props to be passed to children ( How to pass props to {this.props.children} ). 似乎可以接受的方法是使用cloneElement允许将道具传递给孩子( 如何将道具传递给{this.props.children} )。 So the code in the first snippet above: 因此,上面第一个代码段中的代码是:

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

becomes: 变成:

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

I find this rather ugly because it means I am blindly passing all props from my connected app component in to my children route components. 我觉得这很丑陋,因为这意味着我盲目地将所有道具从连接的应用程序组件传递到我的子级路由组件中。

Is this really the accepted way of doing this? 这真的是公认的方法吗?

If you know what props were created in mapStateToProps , you can extract and pass further only them. 如果您知道在mapStateToProps中创建了哪些道具,则可以仅提取并进一步传递它们。

Also, it might be helpful, if you return a single prop with all necessary data from mapStateToProps , let's name it componentState : 另外,如果您从mapStateToProps返回一个包含所有必要数据的道具,那可能会有所帮助,我们将其命名为componentState

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

Then later you can pass only this single prop down 然后,您只能将这个道具向下传递

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

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

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