首页 > 解决方案 > React - 将从 API 获取的数据作为道具传递给组件

问题描述

我正在尝试理解和学习如何将数据作为道具传递给其他组件以供使用。我正在尝试构建一个顶级层次结构,其中 API 请求在顶级类中进行,然后将结果传递给子组件以用作道具,然后在状态中使用。

问题是,当我传递结果时,我的子组件中会出现“Object Promise”如何访问作为道具发送给子组件的数据?

正如您在我的App.js中的 render() 方法中看到的那样,我创建了类 API 的一个组件,并将fetchData()方法的结果作为参数传递给组件。

在我的 API.js 类中,我使用了 console.log 来检查结果,但我从日志中得到的结果是:

第 5 行: {dataObject:承诺}

第 10 行:未定义

应用程序.js:

import API from './API';

class App extends Component {

  componentDidMount(){
    this.fetchData();
  }


  fetchData(){
      const url = "https://randomuser.me/api/?results=50&nat=us,dk,fr,gb";
      return fetch(url)
          .then(response => response.json())
          .then(parsedJSON => console.log(parsedJSON.results))
          .catch(error => console.log(error));
  }

  render() {
    return (
      <div className="App">
        <API dataObject={this.fetchData()}/>
      </div>
    );
  }
}

export default App;

API.js

import React from 'react';

class API extends React.Component{
    constructor(props){
        console.log(props);
        super(props);
        this.state = {
            dataObj:props.dataObject
        };
        console.log(this.state.dataObject)
    }


    render() {
        return(
            <p>""</p>
        )
    }
}

export default API;

标签: javascriptreactjsapi

解决方案


尝试将 App.js 更改为:

import API from './API';

class App extends Component {

  componentDidMount(){
    this.fetchData();
  }


  fetchData(){
      const url = "https://randomuser.me/api/?results=50&nat=us,dk,fr,gb";
      return fetch(url)
          .then(response => response.json())
          .then(parsedJSON => this.setState({results: parsedJSON.results}))
          .catch(error => console.log(error));
  }

  render() {
    return (
      <div className="App">
        <API dataObject={this.state.results}/>
      </div>
    );
  }
}

export default App;

这可以确保您获取数据componentDidMount,它现在用于state存储数据,然后将其传递到您的API组件中。


推荐阅读