简体   繁体   中英

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:

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. 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} ). 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.

Also, it might be helpful, if you return a single prop with all necessary data from mapStateToProps , let's name it 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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