我有addText((,它在点击事件上运行
const [list, setList] = useState([])
const [value, setValue] = useState("")
useEffect(() => {
getObjectItem("tasks")
.then(t => setList(t.item))
.catch(e => { console.log(e) })
}), []
// A function that add data to the list array
function addText(text) {
console.log(list);
if (value !== "") {
setList(prev =>
[...prev,
{ text: text, isSelected: false }] // Adding a JS Object
)
setObjectItem("tasks", list);
setValue("")
} else {
alert("Please type in something!")
}
}
控制台.log(列表(的输出:
Array [
Object {
"isSelected": true,
"text": "Test",
}
]
getObjectItem("tasks"(函数:
const getObjectItem = async (name) => {
try {
const jsonItem = await AsyncStorage.getItem(name)
const item = JSON.parse(jsonItem)
return {
status: 'success',
name: name,
item: item
}
} catch (err) {
return {
status: 'error',
name: name,
error: err
}
}
}
为什么我不能在addText((函数中使用setList()
向现有的list
数组添加值?
设置状态是异步的。
在addText
中,您写道:
setObjectItem("task", list)
它将把AsyncStorage
中的值设置为list
是的值,而不是在状态更新后它将是什么。最简单的解决方案是创建新阵列,然后将其设置为状态和AsyncStorage
。
尝试放置
.then(t=>setList([t.item]((
而不是你写的