在react native中从列表中删除项目并更新新列表



我正在尝试在react native中制作一个to Do应用程序。当从列表中删除一个项目,然后尝试在列表中添加新任务时,整个列表甚至会呈现已删除的项目。下面是我的代码

arr = []
state = {
text : "",
item : [
{id:0,data:"Loading ......"}
]
}
del = (id,data) => {
this.setState({
item: this.state.item.filter(item => item.id !== id)
})
}
storeData = async () => {
this.arr.push({id:Math.random().toString(),data: this.state.text})
await AsyncStorage.setItem('key',JSON.stringify(this.arr))
this.setState({
item: JSON.parse(await AsyncStorage.getItem('key'))
})
}


async componentDidMount() {
this.setState({
item: JSON.parse(await AsyncStorage.getItem('key'))
})
this.arr = JSON.parse(await AsyncStorage.getItem('key'))
}

我甚至试图在del函数中封装storeData函数,但这不起作用。请帮我解决这个问题。

您使用this.arr来存储要存储在AsyncStorage中的项,但在del函数中,您忘记了从this.arr中删除项。在这种情况下,只使用this.state.item就足够了,您不需要this.arrART

del = async (id,data) => {
try {
const newItem = this.state.item.filter(item => item.id !== id)
await AsyncStorage.setItem('key',JSON.stringify(newItem))
this.setState({
item: newItem
})
} catch(err) {}
}
storeData = async () => {
try {
const newItem = [
...this.state.item, 
{id:Math.random().toString(),data: this.state.text}
];
await AsyncStorage.setItem('key',JSON.stringify(newItem))
this.setState({
item: newItem
})
} catch(err) {}
}


async componentDidMount() {
this.setState({
item: JSON.parse(await AsyncStorage.getItem('key'))
})
}

最新更新