Вы должны сделать вызов API в методе componentDidMount
и установить результат в state
компонента.Затем в вашем методе рендеринга вам нужно использовать state
.
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
days: []
};
}
getWeather() {
axios.get(URL)
.then(response => {
this.setState({
isLoaded: true,
days: response //Set the right value here from response
});
}).catch( error => {
this.setState({
isLoaded: true,
error
});
});
}
render() {
const { error, isLoaded, days } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
// your template to show the data goes here
);
}
}
. Обратитесь к документации ReactJS для AJAX здесь .