首页 > 解决方案 > ReactJs - 获取后调用函数

问题描述

我有三个组件;Parent, ChildA, Child B. 父级定义如下:

class Parents extends Component {
   getPersons = () => {
       fetch('/Persons')
        .then(persons => this.setState({ persons:persons })
     }

   updateTable = () => 
       this.setState({ update: true })
 }

现在, ChildA 是我可以创建新 Person 的一种形式。ChildB 是一张显示所有人的表格。当我创建一个新人时,我希望 ChildB 重新渲染。

我尝试在 getPerons() 之后立即在 childA 上调用 updateTable() 函数,如下所示:

class ChildA extends Component {
   onSubmit() {
    this.getPersons();
    this.updateTable();
   }
 }

问题是在获取人员之前更新了表格。处理这个问题的正确方法是什么?

我想可以在 childA 中定义 getPersons(),然后添加“.then(this.updateTable())”,但我也在初始渲染中使用 getPersons,所以我不想将它从 Parent 中移开

标签: javascriptreactjs

解决方案


你不必在同一个地方继续所有的承诺链。第一个函数可以返回承诺,你可以在任何你想要的地方继续这个链。

class Parents extends Component {
   // remove the brackets to return the promise
   getPersons = () => fetch('/Persons')
        .then(persons => this.setState({ persons:persons })

   updateTable = () => 
       this.setState({ update: true })
 }

class ChildA extends Component {
  onSubmit() {
    this.getPersons().then( this.updateTable );
  }
}

推荐阅读