React Native FlatList 项目消失

React Native FlatList Items Disappearing

我有一个模式,用户可以从中选择类别,然后该类别加载到他们个人资料页面上的 FlatList 中。选择第一个类别后,它会以所需的格式正确加载:

当用户从模态窗口中选择并添加第二个项目时,这些项目会消失,如下所示:

并且在添加第三项的时候,提示这个错误:

代码:

用户从中选择的类别数组,挂钩状态:

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 不可见,并且添加第三项后不提示此错误,有人知道为什么会出现这种情况吗?

感谢您的帮助。

看来您的问题出在 catSave 函数的 else 语句中。也许你想这样做?

const catSave = () => {
        if(catData.length > 0){
            if(catsSelected.length < 1){
                setCatsSelected(catData)
            }
            else{
                setCatsSelected([...catsSelected, catData[0]])
            }
        }
        setModalVisible(!modalVisible)
    }

问题

  1. 你正在改变状态
  2. 您将 Array.prototype.push 的结果保存到状态中,这是新的数组长度,而不是更新后的数组
  3. 在后续渲染中,当 catsSelected 不再是一个数组,而是一个数字时,push 方法不存在

Array.prototype.push

The push() method adds one or more elements to the end of an array and returns the new length of the array.

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);
}