javascript - React - 将从 API 获取的数据作为 props 传递给组件

标签 javascript reactjs api

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

问题是,当我传递结果时,我的子组件中得到了 "Object Promise"如何访问作为 props 发送给子组件的数据?

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

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

第 5 行:{dataObject: Promise}

第 10 行:未定义

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 => 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;

最佳答案

尝试将 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组件。

关于javascript - React - 将从 API 获取的数据作为 props 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53290095/

相关文章:

c# - Web 方法与 JavaScript 背后的代码?

javascript - 逗号的空格分隔符 INSTEAD - 大量输出

reactjs - 将父级中的函数绑定(bind)到 react 中子级中的鼠标事件(钩子(Hook))

api - 使用 JavaScript 生成 OAuth 2.0 访问 token

api - 用于行驶距离的 REST API?

javascript - 创建 Javascript 未排序数组对象

javascript - 我如何在 javascript 中遍历 JSON 数组?

reactjs - 带 React Helm 的 Razzle : Meta tags displayed wrong in crawlers when using dynamic values from Axios

reactjs - 我在 react 18 中遇到 i18next 问题

java - 如何从 xml 生成 Edifact 消息?