[英]How can I use an empty array declared on React's initial 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”對象中獲取它。
非常感謝您的幫助,希望您過得愉快!
我已經解決了 我不是將空數組推入列表創建方法的對象中。
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: ''
}
})
}
}
非常感謝大家的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.