我们可以发送从 API 获得的 JSON 作为 child 组件,而不是 object 的每个单独属性吗?

Can we send the JSON obtained from an API as a child component, instead of each individual attribute of the object?

我一直在尝试通过状态将 API 调用获得的数据发送到 child 组件,但它似乎不起作用。

我一直在将 object 的每个单独属性作为 prop 发送到 child 组件。

有没有办法将整个 JSON 响应作为 prop 发送到 child 组件?

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      name: ""
    };
  }
  componentWillMount() {
    this.getWeather();
  }
  getWeather(city) {
    fetch(
      `https://api.apixu.com/v1/current.json?key=2da827a3ce074ddb85417374xxxxxx&q=paris`
    )
      .then(res => res.json())
      .then(data => {
        this.getData(data);
      })
      .catch(err => {
        return Promise.reject();
      });
  }
  getData(data) {
    var location = data.location.name;

    this.setState({ data: data, name: location });
    console.log(this.state.name);
    console.log(this.state.data);
  }
  render() {
    return <Child name={this.state.name} data={this.state.data} />;
  }
}

class Child extends React.Component {
  render() {
    var data = this.props.data;
    return (
      <div>
        <h1>{this.props.name}</h1>
        <h1> {data.current.cloud}</h1>
      </div>
    );
  }
}

ReactDOM.render(<Parent />, document.getElementById("root"));

我希望数据 object 也被传递到 child 但它没有,我得到一个崩溃屏幕,指出数据 object 未定义。

有没有办法将 API 调用中获得的整个 JSON 作为 prop 发送到 child 组件?

您的 Child 组件将在 getWeather api return 数据之前呈现。因此 Child 组件中的 this.props.data 将是 {},当您访问 data.current.cloud 时应用程序崩溃。

你需要检查data是否不为空并且有current属性。所以你的代码应该是

class Child extends React.Component {
  render() {
    var data = this.props.data;
    return (
      <div>
        <h1>{this.props.name}</h1>
        <h1>{data && data.current ? data.current.cloud : ''}</h1>
      </div>
    );
  }
}

在方法“ComponentDidMount”中执行所有 API 调用始终是最佳做法,而不是 "ComponentWillMount"。这将消除您检查响应是否来自 API 的过程。一旦响应到来,组件将被重新渲染。所以,你可以像下面那样做

componentDidMount() {
        this.getWeather();
      }

作为对@tien Duoung 评论的补充,

您可能想要添加一个额外的状态变量。您可以将其命名为 fetchingloading。目的是至少在 api 结果尚未准备好时显示一些内容。可能是这样的:

this.state = { 数据: {}, 姓名: ””, 获取:真实 }

在您的 getData 方法的 .then 中,一旦 data.current 可用,this.setState({ fetching: false })

getData(数据){ 变量位置 = data.location.name;

this.setState({ data: data, name: location, fetching: false });
console.log(this.state.name);
console.log(this.state.data);

}

然后也将 fetching 作为 prop 传递给子组件,当 fetching 为真时,渲染一个加载器组件或说一个占位符 <h1>Loading...</h1>