如何在React组件内顺序调用(A - > B - > C)?

问题描述 投票:2回答:1

我有3个获取函数:a()b(a_id)c(b_id)。函数a将返回a_id并传递给函数b,b将返回id并传递给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()还没有完成取回并得到回复,但bc已经执行,this.props.a_idthis.props.b_id未定义。我无法修改a,b和c函数。

有人知道如何在订单中设置函数调用吗?

javascript reactjs function-call
1个回答
1
投票

您可以使用componentDidMount调用第一个fetch,然后使用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 />
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.