gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:57:42 24 4
gpt4 key购买 nike

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

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

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

问题是:

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

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

最佳答案

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

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

非常感谢大家的帮助!

关于javascript - 如何使用在 React 初始状态中声明的空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53755569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com