我是React的新手,我正在学习如何使用axios通过HTTP获取请求。我指的是youtube视频:https://www.youtube.com/watch?v=NEYrSUM4Umw,后面还有,但出现错误。我认为我有一些小错误,但我无法解决。
import React, { Component } from 'react'
import axios from 'axios'
class PostList extends Component {
constructor(props) {
super(props)
this.state = {
posts: []
}
}
componentDidMount(){
axios.get('https://api.particle.io/v1/devices/64646468431646/temperature?access_token=547376a1b2')
.then(response => {
console.log(response)
this.setState({posts: response.data})
})
.catch(error => {
console.log(error)
}
)
}
render() {
const { posts } = this.state
return (
<div>
temperature
{
posts.length ?
posts.map(post => <div key={post.coreInfo.deviceID}> {post.result} </div>) :
null
}
</div>
)
}
}
export default PostList
当我使用邮差获得HTTP请求时,会收到以下响应:
{ “ cmd”:“ VarReturn”, “ name”:“温度”, “结果”:“ 67.55”, “ coreInfo”:{ “ last_app”:“”, “ last_heard”:“ 2020-04-05”, “已连接”:是的, “ last_handshake_at”:“ 2020-04-05”, “ deviceID”:“ 64646468431646”, “ product_id”:8 }
我的目标是在Web应用程序中显示结果:67.55。
提前谢谢
答案 0 :(得分:1)
如果仅从获取中获取单个对象作为响应,而不是从数组中获取响应,只需将其包装在数组中-
this.setState({posts: [response.data]})