简体   繁体   English

ReactJs-提取后的调用函数

[英]ReactJs - Call function after fetch

I have three components; 我有三个组成部分; Parent, ChildA, Child B. The parent is defined like this: 父级,子级A​​,子级B。父级的定义如下:

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

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

Now, ChildA is a form where I can create new persons . 现在,ChildA是一种形式,我可以创建新的人员 ChildB is a table showing all the persons. ChildB是显示所有人员的表。 I would like ChildB to re render when I have created a new person. 创建新人物后,我希望ChildB重新呈现。

I tried to call an updateTable() function on childA immediately after getPerons(), like this: 我试图在getPerons()之后立即在childA上调用updateTable()函数,如下所示:

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

The issue is that the table is updated before persons are fetched. 问题是在获取人员之前先更新表。 What is the correct way to handle this? 处理此问题的正确方法是什么?

I guess could define the getPersons() in childA and then add ".then(this.updateTable())" but I am using the getPersons in initial rendering as well, so I don't want to move it away from Parent 我想可以在childA中定义getPersons(),然后添加“ .then(this.updateTable())”,但是我也在初始渲染中使用了getPersons,所以我不想将其从Parent移开

You don't have to continue the promise chain all in the same place. 您不必在同一个地方继续承诺链。 The first function can return the promise and you can continue the chain wherever you want. 第一个函数可以返回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 );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM