2016-08-09 33 views
2

通常情況下,您可以訪問父組件發送給子項目的道具。但是,當在子組件上使用redux時,由父節點發送的道具會丟失,並使用將redux狀態與組件道具映射的「connect」方法。訪問道具以及Redux狀態數據發送到組件

如:

聲明與屬性的組件: <A_Component prop1='1' prop2='2' />

訪問無子組件上的終極版,做工精細: this.props.prop1this.props.prop2

相同的語句會給undefined錯誤,如果終極版狀態是用過的。

+0

你能提供一些代碼嗎? – Maxx

回答

4

自己的組件道具可作爲mapStateToProps功能的第二個參數:

// ParentComponent.js 

// ... other component methods ... 
render() { 
    return <TodoContainer id="1" /> 
} 

// TodoContainer.js 

// `ownProps` variable contains own component props 
function mapStateToProps(state, ownProps) { 
    return { 
    todo: state.todos[ownProps.id] 
    }; 
} 
+0

太棒了!完美的作品。 :) –

2

反應-終極版connect method傳遞道具包裹元件。 connect方法可以接收3種方法:

  • mapStateToProps - 創建數據道具
  • mapDispatchToProps - 創建動作道具
  • mergeProps - 結合由2種以前的方法, 產生的道具,並增加了父分配道具(ownProps/parentProps)。

通常只需要重寫mapStateToProps和或mapDispatchToProps,並使用默認mergePropsdefaultMergeProps)。

這是defaultMergeProps方法的定義:

const defaultMergeProps = (stateProps, dispatchProps, parentProps) => ({ 
    ...parentProps, // ownProps 
    ...stateProps, // mapStateToProps 
    ...dispatchProps // mapDispatchToProps 
}) 

所以,除非你通過自己的mergeProps方法來覆蓋defaultMergeProps,您總能獲得由母公司分配的道具。

btw - mapStateToPropsmapDispatchToProps都會收到ownProps,所以他們可以將它們與狀態相結合,並創建新的數據道具/動作道具。