javascript - 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 中移开
解决方案
你不必在同一个地方继续所有的承诺链。第一个函数可以返回承诺,你可以在任何你想要的地方继续这个链。
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 );
}
}
推荐阅读
- ionic-framework - 底部边框/轮廓消失离子卡内的离子按钮
- c - 错误:CentralTendencies.exe 已停止工作,单击代码块中的构建和运行
- android - audioManager.isMusicActive 的监听器
- javascript - React Native Geny Motion 加载问题
- jquery - 在不关闭下拉列表的情况下清除 select2 中的自动完成
- wordpress - 重定向不同的 URL
- java - 交换特定
在 HashMap 中设置 - node.js - 难以通过猫鼬连接到 mongodb
- python - Pytorch:如何在执行机器学习之前格式化数据
- css - Flex 以固定尺寸包裹