首页 > 解决方案 > React将ajax数据传递给孩子

问题描述

如何从 ajax 调用请求的父数据传递给子组件?例如我有这样的代码

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  async componentDidMount() {
    const response = await fetch();

    this.setState(response.data);
  }

  render() {
    return (
        <ChildComponent data={this.state} /> // data={}
    );
  }
}

这里的问题是 ChildComponent 将在获取数据之前挂载,因此我将在 ChildComponent 中获取空对象数据。

标签: javascriptajaxreactjsasync-awaitfrontend

解决方案


检查数据是否可用

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  async componentDidMount() {
    const response = await fetch();

    this.setState(response.data);
  }

  render() { // Return if response is Object
    return Object.keys(this.state).length > 0
      ? <ChildComponent data={this.state} /> // data={}
      : <div>Loading...</div>
  }

  render() { // Return if response is Array
    return this.state.length > 0
      ? <ChildComponent data={this.state} /> // data={}
      : <div>Loading...</div>
  }
}

推荐阅读