我想更改 hasSubmit
键的值,就像在第一个代码部分中一样。我知道不推荐这样做。但是第二个代码是异步的,我不想使用setState
的回调函数。
this.state
和setState
有什么区别?- 有什么方法可以立即更改状态值
hasSubmit
?
First Code:
this.state.hasSubmit = false
this.setState({})
//Code that will use `hasSubmit`.
Second code:
this.setState({
hasSubmit: false,
});
//Code that will use `hasSubmit`.
添加:
场景是:
hasSubmit
setfalse
ingetInitialState()
.hasSubmit
will change tofalse
when I clicksubmit
button.hasSubmit
will change totrue
when submitted.
首先点击submit
没有问题,hasSubmit
会被设置为true
。
但是第二次点击submit
使用Second asynchronous code
会出错,因为hasSubmit
仍然是true
,而 First Code
可以解决问题。
最佳答案
这是 React docs 的内容说:
NEVER mutate
this.state
directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
setState()
does not immediately mutate this.state but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value.There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
setState()
will always trigger a re-render unless conditional rendering logic is implemented inshouldComponentUpdate()
.If mutable objects are being used and the logic cannot be implemented in
shouldComponentUpdate()
, callingsetState()
only when the new state differs from the previous state will avoid unnecessary re-renders.
按照设计的方式使用 API 总是明智的。如果文档说不要改变你的状态,那么你最好不要改变你的状态。
虽然 setState()
在技术上可能是异步的,但它肯定不会以任何明显的方式变慢。组件的 render()
函数将在很短的时间内被调用。
直接设置状态的一个缺点是 React 的生命周期方法 - shouldComponentUpdate()
、componentWillUpdate()
、componentDidUpdate()
- 依赖于使用 setState()
调用状态转换。如果您直接更改状态并使用空对象调用 setState()
,您将无法再实现这些方法。
另一个是它只是糟糕的编程风格。您在两个语句中执行的操作可以在一个语句中执行。
此外,这里没有任何实际好处。在这两种情况下,直到调用 setState()
(或 forceUpdate()
)后,才会触发 render()
。
您声称需要执行此操作,但并未实际解释该需求是什么。也许您想更详细地说明您的问题。可能有更好的解决方案。
最好与框架一起工作而不是反对它。
更新
来自以下评论:
The need is that I want use the changed hasSubmit in below.
好的,我现在明白了。如果您需要立即使用 future 的状态属性,最好的办法就是将它存储在局部变量中。
const hasSubmit = false;
this.setState({
hasSubmit: hasSubmit
});
if (hasSubmit) {
// Code that will use `hasSubmit` ...
关于javascript - ReactJS 中的 this.state 和 this.setstate 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35867038/