[英]how to delay the return in React until fetch is done
我正在使用React js,并想使用Fetch渲染从API获得的数据。 问题是我无法显示获取结果,因为在获取方法完成之前,React执行的返回范围! 请任何我如何解决这个问题的帮助?
这是执行Fetch的功能的一部分:
initFourSquare = () => {
return fetch(FourSquareAPI)
.then(data => {
return data.json()
})
.catch((error) => {
console.log(error.message)
})
};
这是我调用函数(initFourSquare)的react的呈现部分
render() {
var info = []
this.initFourSquare().then(response => {
info = response.response.venues
console.log(info) //the result is appear here
})
setTimeout(function(){ console.log(info[0].name) }, 1000);//the result is appear here
return (
<div>
<h1>{info}</h1> // it display nothing !!!
</div>
);
}
}
相反,不应在render函数中进行任何API /异步调用,如果要一次完成就应该在componentDidMount函数中进行,这似乎是您的情况,并将响应设置为可以在render中使用的状态。 使用状态变量之前,请确保您正确初始化了状态或提供了条件检查是否存在
class App extends React.Component {
state = {
info: []
}
componentDidMount() {
var info = []
this.initFourSquare().then(response => {
info = response.response.venues
this.setState({info})
})
}
initFourSquare = () => {
return fetch(FourSquareAPI)
.then(data => {
return data.json()
})
.catch((error) => {
console.log(error.message)
})
};
render() {
const { info } = this.state;
return (
<div>
<h1>{info}</h1>
</div>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.