首页 > 解决方案 > 如何在 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 函数。

有人知道如何按顺序设置函数调用吗?

标签: javascriptreactjsfunction-call

解决方案


您可以使用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 />
  }
}

推荐阅读