就像这个 fiddle 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();
},
关于javascript - ReactJs:在 this.setState 的情况下不调用回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28853199/