这段代码本质上应该做的是将一个空数组对象与Click函数连接在一起。然后,我想根据子Click的索引分别填充连接每个子数组。因此,每个子列表都有其自己的Click,可以向其自身添加元素。
问题是当我使用setState更新内部subList时,我总是得到错误的输出。直接更改状态时,不会发生这种情况;直接更改状态时,会在控制台窗口中按预期获得正确的结果。
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: []})}
);
}
此函数获取列表和ATTEMPTS的当前索引以分别填充每个子列表 根据被点击的索引。
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.
*/
答案 0 :(得分:1)
由于数组是javascript中的对象,因此您可以像处理对象一样散布数组。
请在此处找到代码-https://codesandbox.io/s/l4z5z47657
//spread array to new object with the Object keys starting from 0 corresponding to each element in array
let tempArray = { ...this.state.List };
//get the array that we need to change and concat to the sublist
let newSubList = tempArray[i];
newSubList.subList = newSubList.subList.concat(0);
//create new array and update the index with new value . Note the special syntax with [i].
//This is because we have spread an array and not an Object
let toChange = { ...tempArray, [i]: newSubList };
//COnvert the Object to array again
toChange = Object.values(toChange);
this.setState({ List: toChange });
console.log(this.state.List);
这将不变地更新状态。您也许可以进一步减少行数,但可以以此作为起点。