因此,我正在阅读article,跌跌撞撞地看到了这个CodePen,并看到在increment
方法中将count
设置为const
,而我m完全无法处理此问题,即如何覆盖const
?谁能解释我所缺少的吗?
state = {
count: 0
};
// Increase count
increment = () => {
const { count } = this.state;
return this.setState({ count: count + 1 });
};
为什么在可以使用const
或let
的情况下声明var
,因为使用const
会令人困惑,因为知道要解构的变量将被操纵?
答案 0 :(得分:2)
您无法重新分配const
。有一个原因将其命名为const
,缩写为constant
。这意味着,一旦定义它,就无法重新分配它。
必须且需要重新分配的变量应声明为let
。
let a = 'a';
a = 'new value'; // this is allowed
const x = 'x';
x = 'new value'; // this is not allowed
var
也可以让您重新分配值,但这是一个旧的表示法,除非在极少数特殊情况下,否则您几乎不需要使用var。
在问题代码中
const { count } = this.state;
计数值从状态中解构并分配给名为count
的变量,这意味着它是值this.state.count
的副本,而不是this.state.count
本身。
答案 1 :(得分:1)
该代码未覆盖 const
的行为。增量的发生不是通过更改 const count
变量的值,而是通过调用 setState
来完成,该方法将(异步)替换组件的整个状态。然后,下一次调用增量或减量时, count
将通过来自 this.state
的解构分配接收新值-这不是变量值的更改,它是每次调用 increment
时新的变量(对于增量函数而言是局部变量)。
答案 2 :(得分:1)
执行<security>
<requestFiltering allowDoubleEscaping="true"/>
</security>
时,实际上是在创建const { count } = this.state;
的副本,而不是直接操纵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);
答案 3 :(得分:-1)
您不能覆盖const的另一种含义是您不能重新分配const。
import colorama
colorama.init()
print_in_green = "\x1b[32m"
print_in_red = "\x1b[31m"
print_in_blue = "\x1b[36m"
print_in_pink = "\x1b[35m"
print_default = "\x1b[0m"
import random
min = 1
max = 6
game_response = input("Would you like to roll your dice (y/n)? ")
if game_response == "y":
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dices...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(print_in_pink)
print(int(dice1))
print(int(dice2))
print(print_default)
score = (int(dice1) + int(dice2))
roll_again = input("Your score for this round is " + str(score) + ". Roll the dices again (y/n)? ")
else:
print("Ok!")
但是您可以修改常量而无需重新分配类型
const a = 1;
a = 2; // you will get TypeError. *** numbers and strings are also immutable
您可以修改,但不能重新分配const。