简体   繁体   中英

React state setter function not changing the state

I am working on a history component in my React project. I have the history state and a setter function setHistory() . I have two functions for handling clicks: handleClick() and removeHistoryItem() , which are called with different buttons. In both of them, I am changing the state with the setHistory() function, but it doesn't work in the handleClick() one.

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)
}

The functions are next to each other so there shouldn't be a problem with the scope. Both functions are executing the other operations well (tested with console.log() , the localStorage is changed just fine, the splice and filter functions are working also). Even the value I am passing to the setHistory() function is correct, just the state is not changed. It's like the setHistory() function is not even called. I am not getting any errors, what could the problem be?

Error is due to Reference equality, both newHistory and history in your handleClick function are referencing same array in "memory", which you mutate with splice , but it is still the same object, react will not detect the change and will not fire the rerender, just because oldValue (history) === newValue (newHistory).

So you need to "recreate" the array in this case. For removeHistoryItem all is ok due to .filter returns the new array already, so new reference, new object.

setHistory([...newHistory]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM