问题描述
我正在制作一个简单的电影监视列表应用程序。 我使用 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));
}
}
}
但这不起作用。 你能告诉我哪里错了吗?
解决方法
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)
请试试这个
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'))