javascript - 为什么在使用 prevState 而不是简单的 setState 时需要进行深拷贝?
问题描述
您在下面看到的代码在我使用时可以正常工作,setState
但是一旦使用prevState
,它就会中断!,我不明白为什么,当然我知道如果我buttonList
像这样复制对象:
const newButtonList = prevState.buttonList.map(item => {
return {...item}
}
这将解决问题,但我仍然不明白为什么以前的解决方案不起作用!
这是完整的代码和沙盒链接:
https
://codesandbox.io/s/goofy-christian-fb3ho?file=/src/Demo.js
代码:onClick1
有效,但 onClick2 无效
import React, { PureComponent } from "react";
class Demo extends PureComponent {
state = {
buttonList: [
{
key: "button1",
enabled: false
},
{
key: "button2",
enabled: false
}
]
};
onClick1 = (callerKey) => {
const newButtonList = [...this.state.buttonList];
const found = newButtonList.find((item) => item.key === callerKey);
found.enabled = !found.enabled;
this.setState({ buttonList: newButtonList });
};
onClick2 = (callerKey) => {
this.setState((prevstate) => {
const newButtonList = [...prevstate.buttonList];
const found = newButtonList.find((item) => item.key === callerKey);
found.enabled = !found.enabled;
return {
buttonList: newButtonList
};
});
};
render() {
return (
<div>
<div
onClick={() => this.onClick1("button1")}
style={{ cursor: "pointer", marginBottom: "100px" }}
>
{`Button1 click on me (${this.state.buttonList[0].enabled})`}
</div>
<div
onClick={() => this.onClick2("button2")}
style={{ cursor: "pointer" }}
>
{`Button2 click on me (${this.state.buttonList[1].enabled})`}
</div>
;
</div>
);
}
}
export default Demo;
解决方案
推荐阅读
- python - 如何提高谷歌云功能的速度?
- azure - Can connect to one Azure DB but not another
- c - Arrays, pointers, and memory management toy example question in C
- javascript - Why isn't the innerHTML changing? Its supposed to count up when clicked
- python - Incorrect element returned from list
- php - logic in meta_query wordpress query
- python - Python 3.6.8: infinite looping forked thread causes no stderr logging on systemd due to default buffering
- c++ - 从中删除项目时如何有效地迭代 std::(unordered)set?
- python - 使用 win10toast 时出错:pywintypes.error: (-2147467259, 'Shell_NotifyIcon', 'Unspecified error')
- java - org.postgresql.util.PSQLException:BigDecimal 类型的值错误:使用 JPA 的 {1}