如何使用在React的初始状态声明的空数组?

时间:2018-12-13 05:39:00

标签: javascript arrays reactjs state

我正在尝试创建一个显示列表列表的应用程序。目前,我一直试图访问首次声明初始状态时声明的空数组。这是我声明的状态:

this.state = {
    newList: {
      category: '',
      items: []
    },
    lists: [],
    itemText: ''
};

“ newList”代表我要推送到“列表”数组中的项目,该列表包含所有列表,如图所示,我使用此方法将“ newList”对象推送到“列表”数组中。 “ itemText”值用作将输入到列表中的文本的占位符,而“ category”则为列表命名。

createListItem(index) {

  //if the value is not empty
  if (this.state.itemText) {

    //create a temporary variable with the list item determined by the index
    let tempList = this.state.lists[index]

    //assign another temporary variable for the "items" array in the list item
    let itemsArray = tempList.items

    //create temporary variable that holds the text that will be pushed into the "items" array
    let newValue = this.state.itemText

    itemsArray.push(newValue)

    this.setState ({
      lists: tempList,
      itemText: ''
    })
  }
}

此方法从无状态组件接收“索引”作为参数,该组件管理列表的呈现。

问题是:

我正尝试访问我推送到“列表”数组中的“ newList”项目的“ items”数组,因为目前它是 undefined 。我试图用一些值预填充数组,但似乎无法在“ newList”对象中获取它。

非常感谢您的帮助,希望您过得愉快!

1 个答案:

答案 0 :(得分:0)

我已经解决了。我不是在列表创建方法中将空数组推入对象。

createCategory() {

if (this.state.newList.category) {

  let existingLists = new Array(...this.state.lists)
  let newList = {...this.state.newList, items: new Array(0)}

  existingLists.push(newList)

  this.setState ({
    lists: existingLists,
    newList: {
      category: ''
    }
  })
 }
}

非常感谢大家的帮助!