![](/img/trans.png)
[英]Does a react component using useState hook rerender every `setState` call?
[英]useState does not rerender
我有一個問題,useState 更新了 state 但在我刷新應用程序之前不顯示更改。 首先,我聲明一個名為 sampleFriends 的數組,由具有字段“name”、“location”和“picture”的對象組成(數組的每個元素看起來類似於:{name: 'John', location: 'Boston',圖片:TestImage})。
然后,我有以下 useState:
const [selectedFriends, setSelectedFriends] = useState([])
在某個時候,我成功渲染
sampleFriends.map(({ name, location, image }, index) => (
<NewMsgTableRow
name={name}
index={index}
location={location}
image={image}
onPress={() => selectFriend(name)}
/>
))
我也有這個 function 就在上面
const selectFriend = name => {
// if the friend is not already selected
if (!selectedFriends.find(e => e === name)) {
const newFriends = selectedFriends
newFriends.push(name)
setSelectedFriends(newFriends)
}
}
組件 NewMsgTableRow 有一個使用 onPress 的按鈕
<TouchableOpacity
onPress={onPress}
>
因此,我想在選擇 selectedFriends 后立即呈現它們(觸摸 TouchableOpacity 並因此更新 state)。 但是,當我單擊該按鈕時,在我編輯並保存我的代碼並自動刷新之前,什么也沒有顯示。 我的理解是 useState 在更新后立即重新渲染組件,但在這種情況下並沒有發生,我不明白為什么。 我一直在讀它是異步的,它不會立即改變它,但我不知道如何讓它工作。 希望它有意義並感謝您的幫助!
您可以使用array spread或Array.concat()進行淺克隆,並添加新項目)所以更改下面的行:
const newFriends = selectedFriends
到這一行:
const newFriends = [...selectedFriends]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.