这段代码基本上应该做的是将一个空数组对象 On Click 与 add 函数连接起来。然后,我想根据子 Click 的索引分别填充连接每个子数组。所以每个 subList 都有自己的 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: []})}
);
}
此函数获取 List 的当前索引并尝试根据单击的索引分别填充每个 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 中的对象。
请在此处找到代码 - 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);
这将永远更新状态。您也许可以进一步减少行数,但以此为起点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句