【发布时间】:2018-08-27 21:49:42
【问题描述】:
这段代码本质上应该做的是将一个空数组对象 On Click 与 add 函数连接起来。然后,我想根据子 Click 的索引分别填充连接每个子数组。所以每个 subList 都有自己的 Click 来给自己添加元素。
问题是当我使用 setState 更新内部子列表时,我不断得到错误的输出。当我直接改变状态时不会发生这种情况,当我直接改变状态时,我会按预期在控制台窗口中得到正确的结果。
import React, { Component } from 'react';
import './App.css';
//onClick: push an array object onto List
//On Sub Click: Fill the inner arrays individually
class AppTest extends Component {
state = {
List: [
{subList: []}
]
}
此函数在每次单击时连接一个数组对象。
add = (event) => {
this.setState(
{List: this.state.List.concat({subList: []})}
);
}
此函数获取列表的当前索引并尝试单独填充每个子列表 基于被点击的索引。
subadd = (i, event) => {
this.setState(
{List: [
{subList: this.state.List[i].subList.concat(0)}
]}
);
//When I mutate state directly, The entire code works as intended: Uncomment below
//to take a look
//this.state.List[i].subList = this.state.List[i].subList.concat(0);
//This is a nested loop that prints the contents of the entire array (including sublists) to the console
for(let i = 0; i < this.state.List.length; i++)
{
console.log(i + "a");
for(let j = 0; j < this.state.List[i].subList.length; j++)
{
console.log(j + "b");
}
}
}
render() {
return (
//My end game is to output input tabs for each element INCLUDING the subList elements in between the main
// List elements
<div>
{this.state.List.map(i => {
return(
<div>
<input value = "Init"/><br />
<div onClick = {this.subadd.bind(this, this.state.List.indexOf(i))}>subClick</div>
</div>
);
})}
<div onClick = {this.add}>Click</div>
</div>
);
}
}
export default AppTest;
/*
All inputs will output the same result: 0a, 0b, 1a, 2a, 3a ...
The length of how many elements are printed is simply the current length of the list.
*/
【问题讨论】:
-
该示例不是嵌套数组。而是一个嵌套对象。我已经尝试过了,但对我的情况没有帮助。
-
还有什么我可以发帖帮忙的吗?
-
您也可以将扩展运算符与数组一起使用。
标签: javascript reactjs