Javascript React-将从API获取的数据作为道具传递给组件

Javascript React-将从API获取的数据作为道具传递给组件,javascript,reactjs,api,Javascript,Reactjs,Api,我试图理解并学习如何将数据作为道具传递给其他组件使用。Iam试图构建一个顶级层次结构,其中API请求在顶级类中发出,然后将结果传递给子组件作为道具使用,然后再传递到状态中 问题是,当我传递结果时,我在我的子组件中得到了“对象承诺”如何访问作为道具发送到子组件的数据? 正如您在my render()方法中的我的App.js中所看到的,我创建了类API的一个组件,并将fetchData()方法的结果作为参数传递给该组件 在我的API.js类中,我使用console.log检查结果,但是 我从日志中得

我试图理解并学习如何将数据作为道具传递给其他组件使用。Iam试图构建一个顶级层次结构,其中API请求在顶级类中发出,然后将结果传递给子组件作为道具使用,然后再传递到状态中

问题是,当我传递结果时,我在我的子组件中得到了“对象承诺”如何访问作为道具发送到子组件的数据?

正如您在my render()方法中的我的App.js中所看到的,我创建了类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”导入API;
类应用程序扩展组件{
componentDidMount(){
这是fetchData();
}
fetchData(){
常量url=”https://randomuser.me/api/?results=50&nat=us,dk,fr,gb”;
返回获取(url)
.then(response=>response.json())
.then(parsedJSON=>console.log(parsedJSON.results))
.catch(错误=>console.log(错误));
}
render(){
返回(
);
}
}
导出默认应用程序;
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;
import API from './API';

function App(props) {

  const [result, setResult] = React.useState({});

  // similar to componentDidMount
  React.useEffect(() => {
    this.fetchData();
  }, []);


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

export default App;
import React from "react";

function API(props) {
  
  const [result, setResult] = React.useState(props.dataObject);

  React.useEffect(() => {
    setResult(result);
  }, [result]);

  return <p>{result}</p>;
}

export default API;
从“React”导入React;
类API扩展了React.Component{
建造师(道具){
控制台日志(道具);
超级(道具);
此.state={
dataObj:props.dataObject
};
console.log(this.state.dataObject)
}
render(){
返回(
“”

) } } 导出默认API;
您应该在
componentDidMount
中获取数据,而不是在
render
中获取数据。在render中获取数据会导致API请求在react.js重新呈现DOM时重复一次

向API端点发出
GET
请求后,首先将数据解析为javascript对象,然后使用组件中的
this.setState将结果设置为
state

从那里,您可以在
渲染
功能中将
状态中保存的数据作为道具传递给子组件

例如:

const App = (props) => 
    <ChildComponent />

class ChildComponent extends React.Component {

    constructor(props){
        super(props);
        this.state = {
            results: []
        }
    }
    componentDidMount(){
        fetch('/api/endpoint')
            .then(res => res.json())
            .then(results => this.setState({results})
    }

    render(){
        return <GrandchildComponent {...this.state} />
    }

}

const GrandchildComponent = (props) => 
    <div>{props.results}</div>
const-App=(道具)=>
类ChildComponent扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
结果:[]
}
}
componentDidMount(){
获取('/api/endpoint')
.then(res=>res.json())
.then(results=>this.setState({results})
}
render(){
返回
}
}
常量组件=(道具)=>
{props.results}

尝试将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;
从“/API”导入API;
类应用程序扩展组件{
componentDidMount(){
这是fetchData();
}
fetchData(){
常量url=”https://randomuser.me/api/?results=50&nat=us,dk,fr,gb”;
返回获取(url)
.then(response=>response.json())
.then(parsedJSON=>this.setState({results:parsedJSON.results}))
.catch(错误=>console.log(错误));
}
render(){
返回(
);
}
}
导出默认应用程序;

这确保您在
componentDidMount
中获取数据,它现在使用
状态
存储数据,然后这些数据将被传递到
API
组件中。

如果有人正在使用钩子寻找答案,这可能会有所帮助

App.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;
import API from './API';

function App(props) {

  const [result, setResult] = React.useState({});

  // similar to componentDidMount
  React.useEffect(() => {
    this.fetchData();
  }, []);


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

export default App;
import React from "react";

function API(props) {
  
  const [result, setResult] = React.useState(props.dataObject);

  React.useEffect(() => {
    setResult(result);
  }, [result]);

  return <p>{result}</p>;
}

export default API;
从“/API”导入API;
功能应用程序(道具){
const[result,setResult]=React.useState({});
//类似于componentDidMount
React.useffect(()=>{
这是fetchData();
}, []);
fetchData(){
常量url=”https://randomuser.me/api/?results=50&nat=us,dk,fr,gb”;
获取(url)
.then(response=>setResult(response.json()))
.catch(错误=>console.log(错误));
}
返回(
);
}
导出默认应用程序;
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;
import API from './API';

function App(props) {

  const [result, setResult] = React.useState({});

  // similar to componentDidMount
  React.useEffect(() => {
    this.fetchData();
  }, []);


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

export default App;
import React from "react";

function API(props) {
  
  const [result, setResult] = React.useState(props.dataObject);

  React.useEffect(() => {
    setResult(result);
  }, [result]);

  return <p>{result}</p>;
}

export default API;
从“React”导入React;
函数API(道具){
const[result,setResult]=React.useState(props.dataObject);
React.useffect(()=>{
setResult(result);
}[结果];
返回{result}

; } 导出默认API;

希望有帮助!如果有任何不正确的地方,请告诉我。

你在App.js类中做了任何更改吗?对我来说,我的类和你的类似乎没有什么区别?通过以这种方式将
获取数据作为道具传递进来,你会导致它在每次渲染组件时触发。@RileySteeleParsons抱歉,我本想更改它,但是解开它。我已经更新了itOk,我会尝试这种方法,但问题是在层次结构的顶层,我不希望类有状态。在这种情况下,我不希望App.js有状态,我希望它是无状态的。只有子组件应该有状态这是一个关于在React组件中使用API的精彩教程:好的,然后制作
app
一个功能性无状态组件,然后将所有API请求委托给子组件,子组件将保存API结果为状态。我的意思是,我可以在顶层有一个状态,但这是做事情的反应方式吗?或者顶层应该始终是无状态的,只有子组件才应该有状态吗?你对您的解决方案?我如何将API请求委托给子组件?我建议您将获取的结果保存在需要数据的组件的最大共同祖先的
状态中。因此,如果您只需要在单个子组件中使用API结果,只需在那里处理请求,并将其存储在其状态中。这样您就可以一个只有一个无状态的
应用程序
组件(您创建