2 回答

TA贡献1815条经验 获得超10个赞
如果您不想混乱componentDidUpdate,您可以使用 setState 回调,该回调在状态更新和重新渲染后被调用。显然,它建议在componentDidUpdate.
this.setState({items: [...this.state.items, ...newItems]},function(){
//gets called after state update and re-rendering.
});

TA贡献1995条经验 获得超2个赞
你可以有一个未解决的承诺,它componentDidUpdate解决了,然后用一个新的代替。然后,在 中addItems,您等待解决当前更新承诺。这样做的一个好处是,如果代码中有多个地方需要在更新发生时得到通知,它们都可以使用相同的 Promise。(您也可以使用添加到然后componentDidUpdate通知的回调数组来实现,但是……这基本上就是 Promise 的作用,如果是 Promise,您可以根据需要使用各种 Promise 组合模式等。)
添加一个方法:
createUpdatePromise() {
this.updatePromise = new Promise(resolve => {
this.resolveUpdatePromise = resolve;
});
}
从您的构造函数调用它。
然后,在componentDidUpdate:
this.resolveUpdatePromise();
this.createUpdatePromise();
addItems:
addItems(newItems) {
this.setState({items: [...this.state.items, ...newItems]});
this.updatePromise()
.then(() => {
// Updated
});
}
添加回答
举报