简体   繁体   English

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

[英]How can I use an empty array declared on React's initial state?

I am trying to create an application that shows a list of lists. 我正在尝试创建一个显示列表列表的应用程序。 I am currently stuck at trying to access an empty array I declared when I first declared the initial state. 目前,我一直试图访问首次声明初始状态时声明的空数组。 Here is the state I declared: 这是我声明的状态:

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

"newList" stands for the item I am pushing into the "lists" array, which holds all of the lists, as it shows, I use this method to push a "newList" object into the "lists" array. “ newList”代表我要推送到“列表”数组中的项目,该列表包含所有列表,如图所示,我使用此方法将“ newList”对象推送到“列表”数组中。 The "itemText" value serves as a placeholder for the text that will input into the list, and "category" names the list. “ 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: ''
    })
  }
}

This method receives "index" as a parameter from a stateless component that manages the rendering of the lists. 此方法从无状态组件接收“索引”作为参数,该组件管理列表的呈现。

The problem is: 问题是:

I am trying to access the "items" array of the "newList" item that I pushed into the "lists" array, because as it is right now, it is undefined . 我正在尝试访问我推送到“列表”数组中的“ newList”项目的“ items”数组,因为就目前而言,它是undefined I have tried to pre-fill the array with some values, but it seems like it just cannot get it inside the "newList" object. 我试图用一些值预填充数组,但似乎无法在“ newList”对象中获取它。

Thank you very much for your help and I hope you have a great day! 非常感谢您的帮助,希望您过得愉快!

I already solved it. 我已经解决了 I wasn't pushing an empty array into the object on the list creation method. 我不是将空数组推入列表创建方法的对象中。

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: ''
    }
  })
 }
}

Thank you all very much for your help! 非常感谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM