Javascript 如何从异步存储中删除选定项?
我正在制作一个简单的电影观察列表应用程序。 我使用异步存储来保存选定的电影。 我想删除用户在观看列表部分选择的电影。现在我正在尝试以下代码:Javascript 如何从异步存储中删除选定项?,javascript,react-native,asyncstorage,Javascript,React Native,Asyncstorage,我正在制作一个简单的电影观察列表应用程序。 我使用异步存储来保存选定的电影。 我想删除用户在观看列表部分选择的电影。现在我正在尝试以下代码: removeItemValue= async (item, index) => { let value1 = await AsyncStorage.getItem('movies'); value1 =JSON.parse(value1); console.log("value1"+value)
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));
}
}
}
但这不起作用。
你能告诉我哪里不对吗
还有我的点击部分:
请尝试
var moviesArray=[{title:'A1'},{title:'A2'},{title:'A3'},{title:'A4'},{title:'A5'},{title:'A6'},{title:'A7'},]
removeSelectedMovie=(名称)=>{
return moviesrarray.filter(item=>item.title.toLowerCase()!==name.toLowerCase())
}
//removeSelectedMovie(此处为MovieName,其将返回//新数组排除选定的电影名称)
console.log(removeSelectedMovie('a1'))
console.log(removeSelectedMovie('a3'))
console.log(removeSelectedMovie('a4'))
console.log(removeSelectedMovie('a7'))
并使用
()=>此.removietemvalue(index)
删除。您的存储只能保存字符串值AsyncStorage.getItem
如果成功,将解析为字符串。您需要使用JSON.parse()
反序列化字符串。只有在正确存储数据(即:作为JSON格式的字符串)的情况下才能执行此操作,这可以使用JSON.stringify()
完成。我添加了您所说的函数并进行了更新
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)
}
}