2017-10-12 89 views
1

我很新的反應,並試圖將我的頭圍繞傳遞狀態包裹到子組件。總之,我有一個包裝組件,其中包含一個顯示錶格的子組件。一旦我將數據存儲在數組中,我將它傳遞給顯示的子項。反應:在傳遞多個狀態時遇到一些問題。

在父我傳遞一個數組是這樣的:

<CustomComponent data={this.state.arrayOne}/> 

然後可以用

this.props.data.map((x,index) => .... etc 

的問題是我多個陣列我需要傳遞給孩子訪問它。因此,如果我的狀態對象如下所示:

this.state = { 
    arrayOne: [], 
    arrayTwo: [], 
    arrayThree: [], 
} 

我該如何去一次通過所有三個?創建這些數組和數組,然後如果有的話,我將如何訪問它們。 this.props.data [0]?

回答

0

你完全可以將多個道具傳遞給一個組件!

<CustomComponent array1={this.state.arrayOne} array2={this.state.arrayTwo}/>

了代碼的整潔我會讓它更簡單,易於閱讀:

render() { 
    const { arrayOne, arrayTwo, arrayThree } = this.state; 
    return (
    <CustomComponent 
     arrayOne={arrayOne} 
     arrayTwo={arrayOne} 
     arrayThree={arrayThree} 
    /> 
); 
}; 

如果你真的希望這一切就象剛剛this.props.data然後將它傳遞這樣: <CustomComponent data={ [...this.state.arrayOne, ...this.state.arrayTwo, ...this.state.arrayThree] } />將所有元素的一個大陣列放在一起。

<CustomComponent data={ [this.state.arrayOne, this.state.arrayTwo, this.state.arrayThree] } />如果你想打電話this.props.data[i]分別而是從一個道具訪問每個陣列 。

+1

喔我不能相信我沒有想到只要做到這一點,它就會根據需要進行工作。我會好奇最佳做法是什麼? – ben54321

-1

有很多方法可以完成你所要求的。我個人會把它作爲一個對象字面量來傳遞。

//destructure the elements you want to pass 
const { arrayOne, arrayTwo, arrayThree } = this.state; 

//pass the data prop as an object literal using property shorthand syntax 
<CustomComponent data={{ arrayOne, arrayTwo, arrayThree }}/> 

並訪問它使用

this.props.data.arrayOne.map(single => single); 
this.props.data.arrayTwo.map(single => single); 
this.props.data.arrayThree.map(single => single); 
0

這種方法通常意味着你傳遞的東西太多<CustomComponent>導致一個大的組件,這不是很重用。

根據您的使用情況,您可能希望創建渲染這些陣列爲表中的每一個「子組件」:

<CustomContainer> 
    <CustomTable data={this.state.arrayOne} /> 
    <CustomTable data={this.state.arrayTwo} /> 
    <CustomTable data={this.state.arrayThree} /> 
</CustomContainer> 
+0

亞在這種情況下,我得到的數據填充父項中的孩子。然後我拿出不同的數據來填充下拉菜單。所以它的整體數據,然後下拉數據,否則我會做你所說的。 – ben54321

相關問題