簡體   English   中英

React state setter function 不改變 state

[英]React state setter function not changing the state

我正在研究我的 React 項目中的歷史組件。 我有history state 和二傳手 function setHistory() 我有兩個處理點擊的函數: handleClick()removeHistoryItem() ,它們是用不同的按鈕調用的。 在這兩個中,我將 state 更改為setHistory() function,但它在handleClick()中不起作用。

const removeHistoryItem = () => {
    const newHistory = history.filter(item => item.id != id)
    setHistory(newHistory)
}
    
 const handleClick = () => {
    let newHistory = history
    let [selectedGame] = history.filter(item => item.id == id)
    const index = history.indexOf(selectedGame)
    
    selectedGame.isFavorite = !selectedGame.isFavorite
    newHistory.splice(index, 1, selectedGame)
    localStorage.setItem('history', JSON.stringify(newHistory))
    setHistory(newHistory)
}

這些功能彼此相鄰,因此 scope 應該沒有問題。這兩個功能都很好地執行其他操作(使用console.log()測試,localStorage 更改得很好,拼接和過濾功能正在運行還)。 即使我傳遞給setHistory() function 的值也是正確的,只是 state 沒有改變。 這就像setHistory() function 甚至沒有被調用。 我沒有收到任何錯誤,可能是什么問題?

錯誤是由於引用相等,handleClick function 中的newHistoryhistory都引用了“內存”中的相同數組,您用splice對其進行了變異,但它仍然是相同的 object,反應不會檢測到更改並且不會觸發重新渲染,只是因為 oldValue (history) === newValue (newHistory)。

所以在這種情況下你需要“重新創建”數組。 對於removeHistoryItem一切正常,因為.filter已經返回新數組,因此新參考,新 object。

setHistory([...newHistory]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM