我正在尝试理解和学习如何将数据作为 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/