Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 反应&x2014;componentDidUpdate作为承诺/回调进行更新。可能吗?_Javascript_Reactjs - Fatal编程技术网

Javascript 反应&x2014;componentDidUpdate作为承诺/回调进行更新。可能吗?

Javascript 反应&x2014;componentDidUpdate作为承诺/回调进行更新。可能吗?,javascript,reactjs,Javascript,Reactjs,我有一个用于更新组件状态的类方法。我希望该方法返回一个承诺,该承诺在组件更新时解析。我打算用于更新组件状态的方法只会在非常特定的情况下调用,因此使用componentdiddupdate的传统方法只会让事情变得非常复杂 一些伪: addItems(newItems) { this.setState({items: [...this.state.items, ...newItems]}); return new Promise(resolve => { this.comp

我有一个用于更新组件状态的类方法。我希望该方法返回一个承诺,该承诺在组件更新时解析。我打算用于更新组件状态的方法只会在非常特定的情况下调用,因此使用
componentdiddupdate
的传统方法只会让事情变得非常复杂

一些伪:

addItems(newItems) {

  this.setState({items: [...this.state.items, ...newItems]});

  return new Promise(resolve => {
    this.componentDidUpdate(() => resolve());
  });

}

有什么建议吗?

您可以有一个未解决的承诺,
componentdiddupdate
解决并用一个新的承诺替换。然后,在添加项中等待当前更新承诺的解决。这样做的一个优点是,如果代码中有多个地方需要在更新发生时得到通知,那么它们都可以使用相同的承诺。(您也可以使用添加到的回调数组,然后
componentdiddupdate
进行通知,但是……这基本上就是承诺所做的,如果是承诺,您可以使用各种承诺组合模式,等等,如果需要的话。)

添加一个方法:

createUpdatePromise() {
    this.updatePromise = new Promise(resolve => {
        this.resolveUpdatePromise = resolve;
    });
}
从构造函数调用它

然后,在
componentdiddupdate
中:

this.resolveUpdatePromise();
this.createUpdatePromise();
附加项

addItems(newItems) {
  this.setState({items: [...this.state.items, ...newItems]});

  this.updatePromise()
  .then(() => {
    // Updated
  });
}

如果您不想混乱
componentdiddupdate
,可以使用setState回调,它在状态更新和重新呈现后被调用。显然,建议在
组件diddupdate
中使用这种逻辑

this.setState({items: [...this.state.items, ...newItems]},function(){
    //gets called after state update and re-rendering.
});