【问题标题】:ReactJs - Call function after fetchReactJs - 获取后调用函数
【发布时间】:2019-06-01 07:26:59
【问题描述】:

我有三个组件; Parent,ChildA,Child 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,所以我不想将它移开家长

【问题讨论】:

  • 什么是this.getTeachers();?
  • @DarrenSweeney - 抱歉,现在编辑到 this.getPersons(); - 我的错误

标签: javascript reactjs


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答。我做了您在 ChildA 中提出的操作并收到“无法读取未定义的属性”错误?不太清楚为什么 - 有什么想法吗?
  • @Alex5207 您还需要更改getPersons 函数以返回fetch。
  • @Baruch - 是的,这似乎是我做错了。不过,不太确定该怎么做。如何在函数中返回获取并仍然设置状态?
  • @Alex5207 请仔细阅读 JJJ 的回答。答案就在示例代码的第二行。
  • 我明白了 - 不知道您可以省略 return 语句。它现在可以工作了,太棒了 - 谢谢你们俩
猜你喜欢
  • 1970-01-01
  • 2018-02-10
  • 2013-09-11
  • 2020-09-21
  • 2018-10-09
  • 2017-04-06
  • 2014-11-22
  • 2021-03-31
相关资源
最近更新 更多