【问题标题】:Use data outside fetch from API ( React )使用从 API (React) 获取之外的数据
【发布时间】:2018-04-23 16:13:14
【问题描述】:
我从 API 获取中接收到一组对象,但是如果我通过汽车,我无法将它传递到 ,它可以工作。
import React from 'react'
import ResponseTable from './responsetable'
var car = [{type:"Fiat", model:"500", color:"white"}];
class Table extends React.Component{
constructor(props){
super(props);
this.state = {};
}
fetchData() {
return fetch('http://localhost:8000/sprints/23')
.then(function(response) {
console.log(response.json);
})
.then(function(myJson) {
return myJson;
});
}
componentDidMount(){
this.fetchData();
}
render(){
return(
<div>
<ResponseTable data={} />
</div>
);
}
}
export default Table;
欢迎任何帮助!
【问题讨论】:
标签:
javascript
reactjs
api
fetch
【解决方案1】:
将响应设置为状态。 car 有效,因为它来自全局范围。
class Table extends React.Component{
constructor(props){
super(props);
this.state = {
data: {}
}
}
fetchData() {
return fetch('http://localhost:8000/sprints/23')
.then(function(response) {
console.log(response.json);
})
.then((myJson) => {
this.setState({data: myJson});
});
}
componentDidMount(){
this.fetchData();
}
render(){
return(
<div>
<ResponseTable data={this.state.data} />
</div>
);
}
}
【解决方案2】:
当您解析获取时,您需要设置您的状态组件,然后将该状态传递给您的 ResponseTable 数据
class Table extends React.Component{
constructor(props){
super(props);
this.state = {
myJson: null // define as null
}
}
fetchData() {
return fetch('http://localhost:8000/sprints/23')
.then((response) => {
console.log(response.json);
})
.then((myJson) => {
this.setState({myJson: myJson})
});
}
componentDidMount(){
this.fetchData();
}
render(){
return(
<div>
<ResponseTable data={this.state.myJson} />
</div>
);
}
}
export default Table;
请注意,我们将myJson 状态设置为空。
然后我们获取数据。我已将 .then 函数更改为箭头函数,以便 this 作用于组件。
然后我们将this.state.myJson 作为属性传递给您的子组件
【解决方案3】:
为什么不将响应放入状态对象中作为道具传递?
import React from 'react'
import ResponseTable from './responsetable'
var car = [{type:"Fiat", model:"500", color:"white"}];
class Table extends React.Component{
constructor(props){
super(props);
this.state = {
data: {}
}
}
fetchData() {
return fetch('http://localhost:8000/sprints/23')
.then(function(response) {
this.setState({data: response.json})
console.log(response.json);
})
}
componentDidMount(){
this.fetchData();
}
render(){
return(
<div>
<ResponseTable data={this.state.data} />
</div>
);
}
}
export default Table;