![](/img/trans.png)
[英]Can't update the array defined with 'useState' in 'useEffect' hook in React-Native
[英]Can't add object to existing array (useState react native)
我有在點擊事件上運行的addText()
const [list, setList] = useState([])
const [value, setValue] = useState("")
useEffect(() => {
getObjectItem("task")
.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("task", list);
setValue("")
} else {
alert("Please type in something!")
}
}
來自console.log(list)的 Output :
Array [
Object {
"isSelected": true,
"text": "Test",
}
]
getObjectItem("任務") function:
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() function 中使用setList()
向現有list
數組添加值?
試着放
.then(t => setList([t.item]))
而不是你寫的
設置 state 是異步的。
在addText
你寫:
setObjectItem("task", list)
這會將AsyncStorage
中的值設置為任何list
,而不是在 state 更新后的值。 最簡單的解決方案是創建新數組,然后將其設置為 state和AsyncStorage
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.