初学React,setState后获取到的thisstate没变,还是初始state?

问题:(javascript)初学React,setState后获取到的thisstate没变,还是初始state?

描述:

          getInitialState(){
            return {data:[]};
          },
          componentDidMount(){
            var data = [ { author: "Pete Hunt", text: "This is one comment" },
                         { author: "Jordan Walke", text: "This is *another* comment" } ];
            (function(data){
              this.setState({data:data});
              console.log(this.state.data);
            }).call(this,data);
          },

为什么log里打出来的data是[]呢?

this.setState 是在 render 时, state 才会改变调用的, 也就是说, setState 是异步的. 组件在还没有渲染之前, this.setState 还没有被调用.这么做的目的是为了提升性能, 在批量执行 State 转变时让 DOM 渲染更快.

另外, setState 函数还可以将一个回调函数作为参数, 当 setState 执行完并且组件重新渲染之后. 这个回调函数会执行, 因此如果你想查看通过 setState 改变后的 state, 可以这样写:

this.setState({myState: nextState}, ()=>{console.log(this.state.myState)})

解决方案1:

React 的 setState 是异步执行的,所以你后面立即 console 是还没改变状态, setState 函数接受两个参数,一个是一个对象,就是设置的状态,还有一个是一个回调函数,就是设置状态成功之后执行的,你可以这样:

(function(data){
   var that = this;
   this.setState({data:data}, function () {
       console.log(that.state.data);
   });
}).call(this,data);

解决方案2:

不能立即 console.log(this.state.data);的,你可以在 render方法里取

解决方案3:

善用官方文档:

void setState(
  function|object nextState,
  [function callback]
)

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

所以正确做法是

this.setState(
    Object.assign({}, { data }),
    () => console.log(this.state)
)