[英]How to fetch data from Instagram api with Axios and Reactjs?
I want to make an api call with Instagram api using Axios/Reactjs i get already data but i am having rendering issue.I don't know where i make mistake but i cant render the caption or image from instagram post.thanks for help.我想使用 Axios/Reactjs 与 Instagram api 进行 api 调用,我已经获得了数据,但我遇到了渲染问题。我不知道我在哪里犯了错误,但我无法渲染来自 Instagram 帖子的标题或图像。谢谢帮助。
import React,{Component} from 'react' import '../styles/home.css' import '../App.css'; import axios from 'axios'; const api = axios.create({ baseURL:`https://graph.instagram.com/me/media?fields=id,caption,media_url&access_token=IGQ.....` }) class Home extends Component { state={ courses: [] } constructor(){ super(); api.get('/').then(res=>{ console.log(res.data) this.setState({courses: res.data}) }) } createCourse = async()=> { let res = await api.post('/', {title:"Test", id:4,autor:'Test'}) console.log(res); } render() { return <div> {this.state.courses.map(course => <h2 key={course.id}>{course.caption}</h2> )} <h1>Hello</h1> </div> } } export default Home; //
You should fetch data in componentDidMount method.您应该在 componentDidMount 方法中获取数据。
componentDidMount() {
api.get('/').then(res => {
console.log(res.data)
this.setState({courses: res.data})
})
}
You're trying to display the data before the fetch was completed.您正在尝试在获取完成之前显示数据。
Change your <div>
from this:从此更改您的
<div>
:
<div>
{this.state.courses.map(course => <h2 key={course.id}>{course.caption}
</h2>)}
<h1>Hello</h1>
</div>
To this:对此:
<div>
{this.state.courses && this.state.courses.map(course => <h2 key={course.id}>{course.caption}
</h2>)}
<h1>Hello</h1>
</div>
So it only renders when data isn't null.所以它只在数据不是 null 时呈现。
-This is happening due to fetching before mounting, so in order to fix that, implement the componentDidMount() method. - 这是由于在安装之前获取而发生的,因此为了解决这个问题,请实现 componentDidMount() 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.