简体   繁体   English

国家得救,但说不是

[英]State saved, but saying its not

I have a react app similar to the default ReactJS tutorial. 我有一个类似于默认ReactJS教程的反应应用程序。

I have a function in a component called after a form is submitted that looks like: 我在提交表单后调用的组件中有一个函数,如下所示:

getInitialState: function () {
  return {
    name: "First Product",
    showOwner: true
  }
},

handleFormSubmit: function (name) {
  console.log(name); //Returns "Hello world"
  console.log(this.state.name); // Returns "First Product"

  this.setState({name: name});
  this.setState({showOwner: false});

  console.log(this.state.name); // Returns "First Product" still
}

For some reason, when I check it out in React developer tools, it shows that this.state.name IS being set to the new value, but when I console.log like shown it still shows the first value instead of "Hello World"? 出于某种原因,当我检查出来的阵营开发工具,它表明this.state.name 设置为新值,但是当我CONSOLE.LOG像表明,它仍然显示的第一个值,而不是“Hello World”的?

From the documentation at https://facebook.github.io/react/docs/component-api.html : https://facebook.github.io/react/docs/component-api.html上的文档:

setState() does not immediately mutate this.state but creates a pending state transition. setState()不会立即改变this.state但会创建挂起状态转换。 Accessing this.state after calling this method can potentially return the existing value. 调用此方法后访问this.state可能会返回现有值。

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. 无法保证对setState的调用进行同步操作,并且可以对调用进行批处理以提高性能。

Also: 也:

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered. 第二个(可选)参数是一个回调函数,它将在setState完成并重新呈现组件后执行。

So, following the documentation, you would want this from your code: 因此,根据文档,您可能希望从您的代码:

handleFormSubmit: function (name) {
  console.log(name); //Returns "Hello world"
  console.log(this.state.name); // Returns "First Product"

  this.setState({
    name: name,
    showOwner: false
  }, function() {
    // Should return "Hello world" after the state has been set.
    console.log(this.state.name);
  }.bind(this));

  // Returns "First Product" still, since setState is not synchronous
  console.log(this.state.name);
}

I don't know react, but that's what the docs say and I have no reason to believe that wouldn't work. 我不知道反应,但这就是文档所说的,我没有理由相信这不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM