setTimeout 和 setState 的关系

栏目: JavaScript · 发布时间: 6年前

内容简介:今天遇到一个问题,业务场景是:表单详情页,用了Because,

问题

今天遇到一个问题,业务场景是:表单详情页,用了 antdForm 组件,想在组件 onChange 时调用 form.validateFields 先校验数据再做提交,过程中, validateFields 一直是延迟的状态,即填了值,在 onChange 中能拿到当前值,但是在 validateFields 的回调中还是上一次的值。在 antdissue 中找到了问题的原因。 https://github.com/ant-design... 关键答案是

Because, setState is asynchronously.

解决方案

issue 中并没有提到解决方案,后来通过尝试用 setTimeout 解决了这个问题。

相关代码链接: https://codesandbox.io/s/unru...

关键代码

handleSelectChange = value => {
    console.log(value);
    this.props.form.validateFields(["gender"], (errors, values) => {
      console.log("inner not setTimeout", values);
    });
    setTimeout(() => {
      this.props.form.validateFields(["gender"], (errors, values) => {
        console.log("inner is setTimeout", values);
      });
    }, 0);
  };

setTimeout 和 setState 的关系

可见 setTimeout 后拿到的值是才正确的。

解释

一个很重要的概念: js是单线程的,单线程就意味着,所有任务需要排队,前一个任务结束,才会执行后一个任务。如果前一个任务耗时很长,后一个任务就不得不一直等着 。空闲时,state 已经更新完成。

解析setTimeout时间设置为0 推荐这篇文章对setTimeout 讲得很透彻


以上所述就是小编给大家介绍的《setTimeout 和 setState 的关系》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pragmatic Thinking and Learning

Pragmatic Thinking and Learning

Andy Hunt / The Pragmatic Bookshelf / 2008 / USD 34.95

In this title: together we'll journey together through bits of cognitive and neuroscience, learning and behavioral theory; you'll discover some surprising aspects of how our brains work; and, see how ......一起来看看 《Pragmatic Thinking and Learning》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

MD5 加密
MD5 加密

MD5 加密工具

html转js在线工具
html转js在线工具

html转js在线工具