javascript – React JS:setState在最后一次输入时迟到了

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

内容简介:翻译自:https://stackoverflow.com/questions/34974775/react-js-setstate-is-late-on-last-input

对不起,如果我不能正确解释我的问题,因为英语不是我的

主要语言.

我创建一个表单组件(用es6编写),如下所示:

class Form extends React.Component {
  constructor(...args) {
    super(args);
    this.state = { input: '' };
  }

  render() {
    return (
      <form>
         <input
           type="text"
           onChange={this.onInputChange.bind(this)}
         />
      </form>
    );
  }

  onInputChange(e) {
    this.setState({ input: e.target.value });
    console.log(`state: ${this.state}, value: ${e.target.value}`); // this is my checking
  }
}

你看到我在哪里操作console.log?现在,当我尝试输入一些东西时

在浏览器上:

// I type this: my word
// on every character input, the output is:

// state: , value: m
// state: m, value: my
// state: my, value: my 
// state: my , value: my w
// state: my w, value: my wo
// state: my wo, value: my wor
// state: my wor, value: my word

// I do backspace
// state: my word, value: my wor
// state: my wor, value: my wo
// state: my wo, value: my w
// state: my w, value: my 
// state: my , value: my
// state: my, value: m
// state: m, value:

看到?每个输入的状态都是迟到的一个字符.这不好

验证输入长度.那我做错了什么?或者,我是否想念

什么?

在setState方法上使用回调.
onInputChange(e) {
    this.setState({ input: e.target.value }, () => {
        console.log(`state: ${this.state}, value: ${e.target.value}`);
    });
}

docs

The second (optional) parameter is a callback function that will be  executed once setState is completed and the component is re-rendered.

翻译自:https://stackoverflow.com/questions/34974775/react-js-setstate-is-late-on-last-input


以上所述就是小编给大家介绍的《javascript – React JS:setState在最后一次输入时迟到了》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

The Lambda Calculus, Its Syntax and Semantics . Revised Edition

The Lambda Calculus, Its Syntax and Semantics . Revised Edition

H.P. Barendregt / North Holland / 1985-11-15 / USD 133.00

The revised edition contains a new chapter which provides an elegant description of the semantics. The various classes of lambda calculus models are described in a uniform manner. Some didactical impr......一起来看看 《The Lambda Calculus, Its Syntax and Semantics . Revised Edition》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具