发布于 2018-11-19 16:44:29
代码没有覆盖const的行为。增量正在发生,不是通过更改const count变量的值,而是通过调用setState来替换(异步)组件的整个状态。然后下一次调用增量或递减时,count将通过this.state的解构赋值接收新值--这不是对变量值的更改,而是每次调用increment时一个新变量(增量函数的局部变量)。
发布于 2018-11-19 16:31:53
您不能重新分配const。它被命名为const ( constant的缩写)是有原因的。这意味着,一旦你定义了它,它就不能重新分配。
必须重新分配并需要重新分配的变量应该声明为let。
let a = 'a';
a = 'new value'; // this is allowed
const x = 'x';
x = 'new value'; // this is not allowedvar还允许您重新分配一个值,但它是一种旧的表示法,除非用于罕见的特定情况,否则通常不需要使用var。
在问题的代码中
const { count } = this.state;计数值从状态中解构,并分配给一个名为count的变量,这意味着它是值this.state.count的副本,而不是this.state.count本身。
发布于 2018-11-19 16:51:06
当您执行const { count } = this.state;时,实际上是在创建副本 of this.state.count,而不是直接操作this.state.count。
除非你需要,否则const是不会意外地操纵它的。
下面的代码片段演示了更新count的“副本”不会更新state.count
(单击Run Code Snippet查看结果)。
const state = { count: 0 };
let {count} = state;
count += 999;
console.log(`state.count`, state.count);
console.log(`count`, count);
而这将失败(不幸)。
const state = { count: 0 };
const {count} = state;
count += 999;
console.log(`state.count`, state.count);
console.log(`count`, count);
https://stackoverflow.com/questions/53378900
复制相似问题