我有一個模式,用戶從中選擇類別,然后該類別加載到他們的個人資料頁面上的 FlatList 中。選擇第一個類別后,它會以所需的格式正確加載:

當用戶從 Modal 中選擇并添加第二個專案時,這些專案會消失,如下所示:

而當添加第三項時,會提示這個錯誤:

代碼:
用戶從中選擇的類別陣列和鉤子狀態:
const [catData, setCatData] = React.useState([])
const [catsSelected, setCatsSelected] = React.useState([])
const categoryData=[
{
id: 1,
name: "CatOne",
},
{
id: 2,
name: "CatTwo",
},
{
id: 3,
name: "CatThree",
}]
用戶選擇他們想要的類別后呼叫的函式:
const onSelectCategory = (itemSelected, index) => {
let newData = categories.map(item => {
if (item.id === itemSelected.id) {
return {
...item,
selected: !item.selected
}
}
return {
...item,
selected: item.selected
}
})
selectedData = newData.filter(item => item.selected === true)
setCatData(selectedData)
}
// Note, the above code is as such due to initially wanting the user to be able to select multiple categories at a time, however,
// I've decided that one category at a time would suffice, and I just modified the above function to fit that need (I will tidy it up later).
用戶確認他們選擇的類別后呼叫的函式:
const catSave = () => {
if(catData.length > 0){
if(catsSelected.length < 1){
setCatsSelected(catData)
}
else{
testData = catsSelected
testData = testData.push(catData[0])
setCatsSelected(testData)
}
}
setModalVisible(!modalVisible)
}
以及所選類別加載到的 FlatList:
<FlatList
data={catsSelected}
horizontal
showsHorizontalScrollIndicator={false}
keyExtractor={item => `${item.id}`}
renderItem={renderCats}
/>
作為參考,這里是正在修改的catsSelected 的控制臺日志:
[] // when it is initialized
[{"id": 1, "name": "CatOne", "selected": true}] // first item added
[{"id": 1, "name": "CatOne", "selected": true}, {"id": 2, "name": "CatTwo", "selected": true}] // second item added, the FlatList is now invisible
// Error prompts after third item is added.
我需要的是讓 FlatList 不可見,并且在添加第三項后不提示此錯誤,有人確定為什么會發生這種情況嗎?
感謝您的幫助。
uj5u.com熱心網友回復:
問題
- 你正在改變狀態
- 您將結果保存
Array.prototype.push到狀態中,這是新的陣列長度,而不是更新的陣列 - 在隨后的渲染中,when
catsSelected不再是陣列,而是數字,該push方法不存在
見Array.prototype.push
該
push()方法將一個或多個元素添加到陣列的末尾并回傳陣列的新長度。
const catSave = () => {
if (catData.length > 0) {
if (catsSelected.length < 1) {
setCatsSelected(catData);
} else {
testData = catsSelected; // <-- reference to state
testData = testData.push(catData[0]); // <-- testData.push mutates state
setCatsSelected(testData); // <-- testData now new array length
}
}
setModalVisible(!modalVisible);
}
解決方案
使用功能狀態更新從前一個統計資料的陣列中正確地將更新排入佇列。淺復制先前狀態的陣列并附加新資料。
const catSave = () => {
if (catData.length) {
setCatsSelected(catsSelected => {
if (catsSelected.length < 1) {
return catData;
}
return [
...catsSelected,
catData[0],
]
});
}
setModalVisible(modalVisible => !modalVisible);
}
uj5u.com熱心網友回復:
看起來您的問題出在 catSave 函式的 else 陳述句中。也許你想這樣做?
const catSave = () => {
if(catData.length > 0){
if(catsSelected.length < 1){
setCatsSelected(catData)
}
else{
setCatsSelected([...catsSelected, catData[0]])
}
}
setModalVisible(!modalVisible)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474621.html
標籤:javascript 数组 反应式 反应钩子 反应本机平面列表
