简体   繁体   English

React state setter function 不改变 state

[英]React state setter function not changing the state

I am working on a history component in my React project.我正在研究我的 React 项目中的历史组件。 I have the history state and a setter function setHistory() .我有history state 和二传手 function setHistory() I have two functions for handling clicks: handleClick() and removeHistoryItem() , which are called with different buttons.我有两个处理点击的函数: handleClick()removeHistoryItem() ,它们是用不同的按钮调用的。 In both of them, I am changing the state with the setHistory() function, but it doesn't work in the handleClick() one.在这两个中,我将 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)
}

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).这些功能彼此相邻,因此 scope 应该没有问题。这两个功能都很好地执行其他操作(使用console.log()测试,localStorage 更改得很好,拼接和过滤功能正在运行还)。 Even the value I am passing to the setHistory() function is correct, just the state is not changed.即使我传递给setHistory() function 的值也是正确的,只是 state 没有改变。 It's like the setHistory() function is not even called.这就像setHistory() function 甚至没有被调用。 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).错误是由于引用相等,handleClick function 中的newHistoryhistory都引用了“内存”中的相同数组,您用splice对其进行了变异,但它仍然是相同的 object,反应不会检测到更改并且不会触发重新渲染,只是因为 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.对于removeHistoryItem一切正常,因为.filter已经返回新数组,因此新参考,新 object。

setHistory([...newHistory]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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