【问题标题】:How to I fill a nested array with setState?如何用 setState 填充嵌套数组?
【发布时间】: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


【解决方案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);

这将不可变地更新状态。您也许可以进一步减少行数,但请以此为起点。

【讨论】:

  • 谢谢!我有一种涉及传播操作员的感觉。这个貌似可以,我回家试试。
猜你喜欢
  • 2015-03-26
  • 2021-10-15
  • 2019-02-24
  • 2020-06-07
  • 2016-03-01
  • 2014-11-05
  • 2018-06-07
  • 2018-07-05
相关资源
最近更新 更多