javascript – ReactJs:在this.setState的情况下不调用回调函数

就像在这个小提琴
http://jsfiddle.net/69z2wepo/3535/中一样,this.setState在componentWillMount中调用,带有回调this.loadData.但函数this.loadData永远不会被称为回调. 最佳答案 我不知道内部是如何工作的,但是查看
setState()的文档……

…you can supply an optional callback function that is executed once setState is completed and the component is re-rendered.

……以及componentWillMount()的文档……

If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

…我认为这与在render()中调用setState()不会重新渲染的事实有关.

鉴于此,对loadData进行初始调用的最合适位置是componentDidMount(),它在初始渲染后立即触发:

componentWillMount() {
  // ...
  this.setState({loaded, data});
},

componentDidMount() {
  this.loadData();
},
点赞