我从一个网站(网址:https://restcountries.eu/rest/v1/)&数据将在控制台中显示。我正在使用“axios”lib来获取数据。 但我想用组件渲染它。怎么做?
这是我的代码。
import React from 'react';
import axios from 'axios';
var Country ;
var fetchData = axios.create({
baseURL: 'https://restcountries.eu/rest/v1/',
});
fetchData.get('https://restcountries.eu/rest/v1/')
.then(
function (response){
console.log(response)
Country = response.data
console.log(Country)
});
console.log(Country);
export default React.createClass({
shouldCompoentUpdate: function(Country,response){
return true;
},
render(){
return(
<div>
<h3>States test</h3>
</div>
)
}
});
答案 0 :(得分:2)
嗯,你做错了。首先,请阅读React Component lifecycle和Loading Initial Data example。您需要在componentDidMount()
挂钩时获取数据并在收到数据时设置状态。
React.createClass({
getInitialState: function() {
return { country: '' }
},
componentDidMount: function() {
var fetchData = axios.create({
baseURL: 'https://restcountries.eu/rest/v1/',
});
fetchData.get('https://restcountries.eu/rest/v1/')
.then(function (response) {
this.setState({ country: response.data});
}.bind(this));
},
render: function() {
return <div>{this.state.country}</div>
}
});