javascript - 我无法通过 useState Hook 从 FlatList 中删除项目

标签 javascript reactjs react-native react-hooks react-native-flatlist

我试图通过单击每个项目来删除 FlatList 中的项目,但这对我不起作用,当我单击每个项目时,什么也没有发生,也没有收到任何错误。 我该如何解决这个问题?

这是我的代码:(我删除了不必要的代码和样式)

const FoodList = () => {


  const data=  [

        { text: 'test' },
        { image: 'https://via.placeholder.com/200x100' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },

    ]




    let [itemState, setitemState] = useState(data);




    return (


        <View>
            <FlatList
                data={data}
                keyExtractor={(item, index)=>index}
                renderItem={({ item }) => (
                    <TouchableOpacity>

                <View>
                        <Text>{item.text}</Text>
                        <Image source={{ uri: item.image}}
                        />
                    </View>
                    <Icon  
                 onPress={(index)=>setitemState(itemState=itemState.filter(item=>item.index!==index))} />
                    </TouchableOpacity>
                )}
 />
 </View>
    )}

最佳答案

首先,正如 @Hamza Khattabi 所提到的,您需要在 data 属性中使用 itemState 来实际使用更新后的状态,否则没有任何使用意义setitemState,仅修改itemState状态。

其次,我认为 item.index 根本不会返回任何内容,而且我非常有信心 onPress={(index) => {...} Icon 元素中的 } 也不会返回任何 index您将可以使用 renderItem 属性中的 index,如 this link 的文档中所述。 .

考虑到这些更改后,您可以简单地过滤掉 itemState 状态以删除索引处的元素。有许多不同的方法可以删除索引处的元素,但这里是一个可能的解决方案:

<FlatList
  data={itemState} // Note the use of itemState
  keyExtractor={(item, index) => index}
  renderItem={({ item, index }) => ( // Note the use of index
    <TouchableOpacity>
      <View>
        <Text>{item.text}</Text>
        <Image source={{ uri: item.image }} />
      </View>
      <Icon
        onPress={() => { // Note that here you can use any function to remove the element at index from the itemState list
          let _itemState = itemState.filter(
            (_item, _index) => _index !== index
          );
          setitemState(_itemState);
        }}
      />
    </TouchableOpacity>
  )}
/>

请在下面发表评论,让我知道这是否对您有帮助。

关于javascript - 我无法通过 useState Hook 从 FlatList 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60551607/

相关文章:

javascript - 应测试 MERN 堆栈应用程序的哪一部分?

javascript - react 拖放区 : Get data:images after upload

reactjs - 如何通过 jest.setup.js 中的配置修复 Enzyme 上的 "SyntaxError: Unexpected identifier"

javascript - React 不渲染 AJAX 数据

javascript - Android Studio React Native 构建失败

javascript - 检查函数是否在 Ajax 和 WebMethod 中返回任何数据

php - 使用浏览器后退按钮获取 Ajax 上一个请求

javascript - 在 Jasmine 中 mock Angular $元素

javascript - 如何使用 React Native 动态显示图像

ios - 为什么 React Native iOS 模拟器的重新加载快捷方式有时会停止工作?