简体   繁体   English

为什么React状态是初始化状态而不是我刚刚设置的状态?

[英]Why is React state the init state and not the state I just set?

I have the following code: 我有以下代码:

var Try = React.createClass({displayName: "Try",
  getInitialState: function() {
    return {
        int: 'x'
    };
  },
  ck: function() {
    this.setState({int: 1});
    console.log(this.state.int);
  },
  render: function() {
    return (
      React.createElement("div", {onClick: this.ck}, "Hello")
    );
  }
});

React.render(React.createElement(Try, null), $('body')[0]);

Try it here: http://codepen.io/rlog/pen/qdvVEK/ 在这里尝试: http : //codepen.io/rlog/pen/qdvVEK/

When I click Hello div for the first time, the log is x . 当我第一次单击Hello div时,日志为x Why isn't it 1 ? 为什么不是1

According to the documentation: 根据文档:

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的调用的同步操作,并且可能会为提高性能而批量调用。

setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). 除非在shouldComponentUpdate()中实现了条件渲染逻辑,否则setState()将始终触发重新渲染。 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. 如果正在使用可变对象,并且逻辑不能在shouldComponentUpdate()中实现,则仅当新状态不同于先前状态时才调用setState()可以避免不必要的重新渲染。

Component API @ React docs 组件API @ React docs

You can use optional second parameter that is a callback function to get the changed value after the setState is completed. 您可以使用可选的第二个参数(它是一个回调函数)在setState完成后获取更改的值。

this.setState({int: 1}, function () {
  console.log(this.state.int)
}); 

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

http://codepen.io/anon/pen/JdzONa http://codepen.io/anon/pen/JdzONa

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

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