首页 > 解决方案 > 反应原生从数组列表中删除一个项目

问题描述

我正在尝试从反应本机的列表中删除一个项目,但它不起作用

handleDeletePost = (passedItem) => {
  const { userPosts } = this.state;
  const newArray = userPosts.map(item => {
  if (item.headline === passedItem.headline) {

  Alert.alert(
    'Delete Post',
    'Are you sure to delete Post?',
    [
      {text: 'Yes', onPress: () => console.log('Ask me later pressed')},
      {text: 'No', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}
    ],
    { cancelable: false }
  )
  }
});
}

当我点击删除时出现错误:找不到变量索引

标签: reactjsreact-native

解决方案


您的地图看起来没有正确使用,但要从数组中删除项目,请使用 .splice() 函数。

例子

var array = [2, 5, 9];
console.log(array)
var index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

输出

array[2, 9]

希望这可以帮助 :)


推荐阅读