【发布时间】: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