javascript - ReactJS 中的 this.state 和 this.setstate 有什么区别?

标签 javascript reactjs asynchronous

我想更改 hasSubmit 键的值,就像在第一个代码部分中一样。我知道不推荐这样做。但是第二个代码是异步的,我不想使用setState的回调函数。

  • this.statesetState 有什么区别?
  • 有什么方法可以立即更改状态值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`.

添加:

场景是:

  1. hasSubmit set false in getInitialState().
  2. hasSubmit will change to false when I click submit button.
  3. hasSubmit will change to true 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. Accessing this.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 in shouldComponentUpdate().

If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() 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/

相关文章:

javascript - setTimeout 在 react setState 中

reactjs - 无法将状态数据作为 Prop 发送到另一个组件

php - 如何在 PHP PDO 中使用异步 Mysql 查询

用于在非 SPA 站点上构建可重用组件的 Javascript MVC 框架

javascript - For 循环和更新函数在 React 中不起作用

javascript - 异步调用nodejs和python

web-services - 限制并发Web Service请求(或某些批处理方法)

javascript - 在 react 中从同一文件导入多个组件而不是导入每个组件的正确方法是什么

javascript - 为什么使用 ES6 Map 而不是普通的 javascript 对象?

javascript - 回调后的值如何使用