【问题标题】:How can i remove a selected item from asyncstorage?如何从 asyncstorage 中删除选定的项目?
【发布时间】:2021-01-04 13:51:22
【问题描述】:

我正在制作一个简单的电影观看列表应用程序。 我使用 asyncstorage 来保存选定的电影。 我想删除用户在关注列表部分中选择的电影。现在我正在尝试这段代码:

    removeItemValue= async (item, index) => {
    let value1 = await AsyncStorage.getItem('movies');
    value1 =JSON.parse(value1);
    console.log("value1"+value)
    //value = item.splice(index,1)
    if (value1 !== null){
        //var index = value.indexOf(x => x.Title === item.Title);
        if (index > -1){
        value1.splice(index, 1);
        await AsyncStorage.removeItem('movies');
        
        AsyncStorage.setItem('movies',JSON.stringify(value)); 
        
    }
    }       
    
}

但这不起作用。 你能告诉我哪里错了吗?

也是我的点击部分:

【问题讨论】:

  • 您的存储只能保存字符串值。 AsyncStorage.getItem 如果成功,将解析为字符串。您需要使用JSON.parse() 反序列化字符串。只有正确存储数据(即:作为 JSON 格式的字符串)才能执行此操作,这可以使用 JSON.stringify() 来完成。
  • 我添加了你说的功能并更新了

标签: javascript react-native asyncstorage


【解决方案1】:
removeItemValue = async(index) => { // don't need item here
  // avoid mutations, create new variables
  const rawValue = await AsyncStorage.getItem('movies');
  try {
    const jsonValue = JSON.parse(rawValue) || []; // avoid undefined or null
    const finalValue = [...jsonValue.slice(0, index), ...jsonValue.slice(index + 1)];
    await AsyncStorage.setItem('movies', JSON.stringify(finalValue)); // add await here
  } catch (e) {
    console.log('Parsing failed', e)
  }
}

并使用() => this.removeItemValue(index)删除

【讨论】:

    【解决方案2】:

    请试试这个

    var moviesArray = [{title:'A1'},{title:'A2'},{title:'A3'},{title:'A4'},{title:'A5'},{title:'A6'},{title:'A7'},]
    
    removeSelectedMovie=(name)=>{
    return moviesArray.filter(item=>item.title.toLowerCase() !== name.toLowerCase())
    }
    
    //removeSelectedMovie(MovieName here and its will return a //new array excluded selected movie name)
    console.log(removeSelectedMovie('a1'))
    console.log(removeSelectedMovie('a3'))
    console.log(removeSelectedMovie('a4'))
    console.log(removeSelectedMovie('a7'))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 2019-01-18
      • 2013-09-14
      • 2014-10-14
      • 2017-06-18
      相关资源
      最近更新 更多