ReactJs-提取后的调用函数

时间:2019-01-06 10:39:33

标签: javascript reactjs

我有三个组成部分;父级,子级A​​,子级B。父级的定义如下:

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

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

现在,ChildA是一种表单,我可以在其中创建新的 persons 。 ChildB是显示所有人员的表。我希望ChildB在创建新人后重新呈现。

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

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

问题在于,在提取人员之前更新了表。 处理此问题的正确方法是什么?

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

1 个答案:

答案 0 :(得分:3)

您不必在同一位置继续承诺链。第一个函数可以返回promise,您可以在任意位置继续链。

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 );
  }
}