javascript - 如何在 React 组件中按顺序调用(A -> B -> C)获取?
问题描述
我有 3 个获取函数:a()
, b(a_id)
, c(b_id)
. 函数 a 将返回 ana_id
并传递给函数 b,b 将返回 anid
并传递给 c。
componentDidUpdate(prevProps) {
this.gotoanotherPage(this.props.a_id);
}
generateBody() {
this.props.a();
this.props.b(this.props.a_id);
this.props.c(this.props.b_id);
}
render() {
body = generateBody();
return <framework {body}/>
}
我的问题是a()
尚未完成获取并获得响应,但b
已经c
执行并且this.props.a_id
未定义this.props.b_id
。我无法修改 a、b 和 c 函数。
有人知道如何按顺序设置函数调用吗?
解决方案
您可以使用componentDidMount
调用第一个提取,然后使用componentDidUpdate
调用依赖于第一个提取的第二个提取。然后对第三次取回做同样的事情。
您可以使用prevProps
来检查您是否收到了第一个和第二个响应。
您的组件将看起来像这样:
class MyComponent extends Component {
componentDidMount() {
this.props.fetchA();
}
componentDidUpdate(prevProps) {
if (!prevProps.a_id && this.props.a_id) { // it means you received a_id
this.props.fetchB(this.props.a_id);
}
if (!prevProps.b_id && this.props.b_id) { // it means you received b_id
this.props.fetchC(this.props.b_id);
}
}
render() {
return <framework />
}
}
推荐阅读
- php - Symfony 表单不向控制器发送文件
- selenium - 如何用列表忽略跨度
- reactjs - 登录页面不使用 React Router ProtectedRoute 呈现
- bash - openssl pass 参数是否通过 bash 安全?
- angular - 解决 Angular/Typescript 中的循环依赖
- delphi - 在 DELPHI 中为 AVPlayer 设置用户代理
- ssl - 如何从 Power bi 桌面连接到 DB2 数据库,以及当 DB2 托管在启用了 SSL 端口的 VM 中时?
- java - 聊天应用程序中的反向分页不起作用
- python - 如何在没有 VNC 的情况下远程控制 Raspberry Pi
- css - 使用垫子菜单在悬停按钮上显示问题;活动按钮在点击时消失