reactjs - 为什么我们需要将 this 变量设置为展开运算符?需要这条线吗?
问题描述
在下面的代码中,我不明白为什么我们需要下面的行,如果 counters 已经等于状态。在做什么?我可以删除该行吗?
counters[index] = { ...counters[index] };
这就是全部。
class App extends Component {
state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counters[index] };
counters[index].value++;
this.setState({ counters });
};
解决方案
最初的意图似乎是创建一个看起来与原始对象相同的新对象(复制所有属性),但这样做是为了避免改变原始状态。
我怀疑如果没有这条线,它似乎“工作正常”,但 React 状态旨在是不可变的。
推荐阅读
- reactjs - 在 HoC 中使用反应钩子时的警告
- java - 从现有类生成 jOOQ 表
- spring-data-jpa - Which sorting method is efficient among sorting using JPA order by or sorting using collection sort() method?
- c++ - x64 C++ 可执行文件未在 nanoserver docker 容器中运行
- java - 检查 char 列表的元素是否在字符串中
- css - 如何在 Swiper Slider 中编辑 translate3d
- python - 将 BoxSelectTool cb_data 选择传递给 Bokeh Server 中的 Python 代码
- reactjs - 我正在尝试使用 axios 和 django 从 TODO 应用程序中删除项目
- iot - SIM7020E 响应 AT+COPS=? 有错误
- c# - 如何使 redis 缓存在 IIS Express 上部署的 asp.net core web 上工作,但在 localhost 上工作