如何从FlatList中的存储中删除项目?

时间:2019-02-07 11:15:00

标签: react-native expo asyncstorage

我的存储设备中有字符串,我想创建一个删除按钮,以删除存储设备中的密钥。我的问题是我在flatList中,无法管理它。

async removeItemValue(key) {
try {
  await AsyncStorage.removeItem(key);
  return true;
}
catch(exception) {
  return false;
}

}

render() {
return (
<View style={styles.container}>
  <View>
    <FlatList
      data={this.state.imgData}
      renderItem={({item}) => 
        <View style={{flex: 1, alignItems: "center", justifyContent: "center", marginBottom: 20, borderBottomColor:"white", borderBottomWidth:1}}>
          <Text>{item.date}</Text>
          <Image style={{width: 300, height: 350}} source={{ uri: item.key }} />
          <TouchableOpacity style={styles.menuButton} onPress={this.removeItemValue(item.key)}>
            <Text>Delete</Text>
          </TouchableOpacity>
        </View> 
      }
    />
  </View>
</View>
);

} }

您能否同时向我解释为什么在加载此页面时而不是仅在单击按钮时调用touchableOpacity中的OnPress方法?

3 个答案:

答案 0 :(得分:2)

关于onPress,您在编译时调用该函数。 onPress={this.removeItemValue(item.key)}。您必须在此处发送回调,例如:

onPress={() => {console.log("pressed")}}

在您的情况下 onPress={() => {this.removeItemValue(item.key)}}

答案 1 :(得分:1)

将渲染方法替换为此

render() {
return (
<View style={styles.container}>
  <View>
    <FlatList
      data={this.state.imgData}
      renderItem={({item, index}) => 
        <View style={{flex: 1, alignItems: "center", justifyContent: "center", marginBottom: 20, borderBottomColor:"white", borderBottomWidth:1}}>
          <Text>{item.date}</Text>
          <Image style={{width: 300, height: 350}} source={{ uri: item.key }} />
          <TouchableOpacity style={styles.menuButton} onPress={() => this.removeItemValue(item.key)}>
            <Text>Delete</Text>
          </TouchableOpacity>
        </View> 
      }
    />
  </View>
</View>
);

在映射时,您需要使用箭头函数进行回调

如果要从数组对象中删除任何值,请使用onPress按钮中的index,以便可以使用索引轻松删除任何值。

  • 确保从存储中删除值后,请更新状态 因为您在平面列表中具有渲染状态,并且已从存储中删除。

答案 2 :(得分:0)

如果您将发送的道具定义为(箭头)功能,它应该可以工作:

onPress={() => this.removeItemValue(item.key)}

如果您发送这样的道具...

 onPress={this.removeItemValue(item.key)}

...那么您就不再发送函数,而是发送this.removeItemValue(...)函数返回的 value 。该函数在传递给组件之前执行。