gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:31 24 4
gpt4 key购买 nike

就像这个 fiddle http://jsfiddle.net/69z2wepo/3535/ this.setStatecomponentWillMount 中通过回调 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com