首页 > React setState 后调用组件方法时读取到的state没有变化?

React setState 后调用组件方法时读取到的state没有变化?

简单把这部分困惑的拆出来做了一个小demo,jsbin地址是 http://jsbin.com/qovudawiho/edit?html,js

简单来说就是子组件调用props上的方法来修改父组件的state,修改之后,调用父组件的fetch()方法获取新数据来更新render,但是子组件触发动作后父组件的state却没有更新,所以fetch时传入的state也不是最新的,求解

demo里表现为componentDidMount 时 alert(null), 第一次点击button时还是alert(null),之后才会alert(100), 求解


setState 是异步的,但是提供了 state 改变后的回调

handleCB(val) {
    this.setState({
      id: val
    }, () => {
        this.fetch()
    });
  }

setState是异步的
详情见 https://facebook.github.io/react/docs/component-api.html

Notes: NEVER mutate this.state directly, as calling setState()
afterwards may replace the mutation you made. Treat this.state as if
it were immutable. setState() does not immediately mutate this.state
but creates a pending state transition. Accessing this.state after
calling this method can potentially return the existing value. There
is no guarantee of synchronous operation of calls to setState and
calls may be batched for performance gains. setState() will always
trigger a re-render unless conditional rendering logic is implemented
in shouldComponentUpdate(). 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.


回调函数, period.

【热门文章】
【热门文章】