【发布时间】:2019-04-16 19:44:52
【问题描述】:
我正在尝试了解和学习如何将数据作为道具传递给其他组件以供使用。我正在尝试构建一个顶级层次结构,其中 API 请求在顶级类中发出,然后将结果传递给子组件以用作道具,然后在状态中使用。
问题是,当我传递结果时,我在子组件中得到 "Object Promise"。 如何访问作为 props 发送给子组件的数据?
您可以在我的 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.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;
【问题讨论】:
标签: javascript reactjs api