2017-10-12 32 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

相关问题