我有一个带有值的数组,我使用forEach将值作为道具传递给组件。我还想发送一个值作为props,并在每次迭代时将其增加1。目前,我已经尝试过:
this.state = {
index: 0
}
let news:any[] = []; //container for other items for the loop
let indx = this.state.index;
this.state.listItems.forEach((myArrWItems) => {
indx = +1;
news.push(<MyComponent
index = {indx}
/>);
});
但是,作为道具发送的值始终为1。有帮助吗?
答案 0 :(得分:1)
您永远不会更新index
变量,只是将+1分配给永不突变的indx
变量。您需要更新状态并以这种方式增加indx
变量,然后将值推入setState
回调中的数组,但是我建议您在{{1 }}循环,因为这是完成您想要做的事情的最佳方法:
forEach
答案 1 :(得分:1)
您的index
状态变量在那里不是必需的。由于要从现有数组创建数组,因此应使用map
函数,如官方文档中所示。
此函数会将元素的index
作为第二个参数直接带入其回调。
您的编码可以简化为一行:
const news = this.state.listItems.map((item, index) => <MyComponent key={index} index={index + 1}/>)
在制作数组时,请不要忘记设置组件的key
属性。
<MyComponent index/>
语法是<MyComponent index={index}/>
的简短版本