React:正在更新处于状态的对象的属性

React: updating property of object in state

本文关键字:状态 对象 属性 于状态 更新 React      更新时间:2023-09-26

我有一个组件,它将文档作为状态aDocuments进行跟踪。单击按钮后,文档即被上载。每个文档对象都包含处理上载的功能。在上传过程中,文档中的模式从"新建"更改为"上传完成"。文档对象在上载过程中更新模式。每个文档都是来自aDocuments数组中处于我状态的对象的引用。

当处于状态的对象可以更新自身时,我如何正确处理该对象的更新属性?我的setState调用只会导致渲染。

Doc.prototype.upload = function (uploadComplete) {
  if (this.mode === 'new') {
    this.mode = 'uploading';
    // do uploading stuff and call uploadComplete after upload is finished
    $.ajax(..., complete: function() {
      this.mode = 'done';
      uploadComplete(this); 
    });
  }
}
// in my component
clickHandler: function (doc) {
  doc.upload(function(tmpDoc) {
    // this will cause render to show the doc as done
    this.setState('aDocuments', this.state.aDocuments);
  });
  // this will show the document as uploading
  this.setState('aDocuments', this.state.aDocuments);
}

如有任何帮助,我们将不胜感激。

为了更新文档数组所在的顶级组件的状态,您需要通过props(修改顶级文档数组)向各个文档组件传递回调函数。