【问题标题】:How can I use an empty array declared on React's initial state?如何在 React 初始状态下使用空数组声明?
【发布时间】:2019-05-14 07:10:10
【问题描述】:

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

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

“newList”代表我要推入“lists”数组的项目,该数组包含所有列表,如图所示,我使用此方法将“newList”对象推入“lists”数组。 “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: ''
    })
  }
}

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

问题是:

我正在尝试访问我推入“lists”数组的“newList”项的“items”数组,因为它现在是未定义。我试图用一些值预先填充数组,但它似乎无法将它放入“newList”对象中。

非常感谢您的帮助,希望您有美好的一天!

【问题讨论】:

  • 您能否显示最初将项目放入lists 的代码?
  • 当然! ` createCategory() { if (this.state.newList.category) { let existingLists = new Array(...this.state.lists) let newList = this.state.newList existingLists.push(newList) this.setState ({列表:现有列表,新列表:{ 类别:'' } }) } } `

标签: javascript arrays reactjs state


【解决方案1】:

我已经解决了。我没有将空数组推入列表创建方法中的对象中。

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

非常感谢大家的帮助!

【讨论】:

    猜你喜欢
    • 2018-12-20
    • 1970-01-01
    • 2016-01-23
    • 2022-12-09
    • 1970-01-01
    • 2011-03-06
    • 2017-09-24
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多