簡體   English   中英

使用Redux的React Router:僅將必要的道具傳遞到子級路由

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

我有一個連接到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)

應用是我的反應路由器層次結構中的根級組件,因此接收所有子路由作為子路由:

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

我希望能夠將通過mapStateToProps傳遞到App的道具傳遞給子組件。 似乎可以接受的方法是使用cloneElement允許將道具傳遞給孩子( 如何將道具傳遞給{this.props.children} )。 因此,上面第一個代碼段中的代碼是:

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

變成:

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

我覺得這很丑陋,因為這意味着我盲目地將所有道具從連接的應用程序組件傳遞到我的子級路由組件中。

這真的是公認的方法嗎?

如果您知道在mapStateToProps中創建了哪些道具,則可以僅提取並進一步傳遞它們。

另外,如果您從mapStateToProps返回一個包含所有必要數據的道具,那可能會有所幫助,我們將其命名為componentState

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

然后,您只能將這個道具向下傳遞

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM