[英]Why is this counted as mutating state?
handleClick(event) {
let value = event.target.value;
this.setState({ question: (this.state.question += value) });
I get a warning: 我收到警告:
Do not mutate state directly.
不要直接改变状态。 Use setState() react/no-direct-mutation-state
使用setState()react / no-direct-mutation-state
if I try to load the page with this code. 如果我尝试用此代码加载页面。
How can I fix it so it doesn't give me this warning? 我该如何解决,以免出现警告?
It says to use this.setState
, but that's what I'm doing. 它说使用
this.setState
,但这就是我在做的。
You're doing an unnecessary assignment addition to this.state.question
- you only need addition here. 您正在为
this.state.question
做不必要的分配 -您只需要在此处添加即可。 Furthermore, when updating state based on a previous value, the docs state : 此外,当根据先前的值更新状态时, 文档状态为 :
React may batch multiple setState() calls into a single update for performance.
React可以将多个setState()调用批处理到单个更新中以提高性能。 Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
由于this.props和this.state可以异步更新,因此您不应依赖于它们的值来计算下一个状态。
The proper way to update state based on a previous value is to pass in an update function that works off the previous value, ie: 根据先前的值更新状态的正确方法是传入更新函数,该更新函数以先前的值为准,即:
this.setState(prevState => ({ question: prevState.question + value }));
The mistake is here : 错误在这里:
this.state.question += value
+= is the operator used to add right operand to the left operand. + =是用于将右操作数添加到左操作数的运算符。 You are trying to add value to this.state.question.
您正在尝试为this.state.question添加值。
The correct way to do it is : 正确的方法是:
this.setState(previousState => ({ question: previousState.question + value }));
This is considered mutating state because you are assigning a value to this.state.question
in the expression (this.state.question += value)
. 这被认为是变异状态,因为您正在为
this.state.question
中的this.state.question
分配一个值(this.state.question += value)
。 I have pasted a link to a Code Sandbox you can view to see how to correctly implement this behavior. 我已经粘贴了指向代码沙箱的链接,您可以查看该代码沙箱以查看如何正确实现此行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.