在axios GET请求中获取空对象
Getting empty object in axios GET request
我正在从 WordPress 博客站点提取帖子。但是当我在 .then()
中控制日志状态 posts
和 response
时,我得到 Response
作为 empty object [object object]
和 state
作为 undefined
。
我哪里错了?
我也收到以下错误:
TypeError: Cannot read property 'map' of undefined
代码:
import React, {Component} from 'react';
import axios from 'axios';
import Post from './Post/Post';
class Blog extends Component {
state = {
posts: []
}
componentDidMount(){
axios.get("https://public-api.wordpress.com/rest/v1.1/sites/ishhaanpatel.wordpress.com/posts")
.then( response => {
this.setState({posts: response.posts});
console.log("Here are the posts: "+ this.state.posts);
console.log("Here is the response: "+ response);
});
}
render(){
const posts = this.state.posts.map( post => {
return <Post title={post.title} key={post.ID} author={post.author.name} />;
});
return (
<div>
{posts}
</div>
);
}
}
export default Blog;
您的数据嵌套在 response.data
对象中。
更新
this.setState({posts: response.posts});
到
this.setState({posts: response.data.posts});
Axios returns 包含有关响应的附加信息的 HTTP 响应对象。
您遇到 asyncronous
的问题。
setState
是 async
。因此,您不会立即获得 this.state.posts
.
中的值
要解决此问题,您可以使用回调,如下所示:
this.setState({ posts: response.posts }, () => {
console.log(this.state.posts);
});
您的帖子也嵌套在 response.data
中。因此,您的 setState
应该类似于:
this.setState({ posts: response.data.posts }, () => {
console.log(this.state.posts);
});
我正在从 WordPress 博客站点提取帖子。但是当我在 .then()
中控制日志状态 posts
和 response
时,我得到 Response
作为 empty object [object object]
和 state
作为 undefined
。
我哪里错了?
我也收到以下错误:
TypeError: Cannot read property 'map' of undefined
代码:
import React, {Component} from 'react';
import axios from 'axios';
import Post from './Post/Post';
class Blog extends Component {
state = {
posts: []
}
componentDidMount(){
axios.get("https://public-api.wordpress.com/rest/v1.1/sites/ishhaanpatel.wordpress.com/posts")
.then( response => {
this.setState({posts: response.posts});
console.log("Here are the posts: "+ this.state.posts);
console.log("Here is the response: "+ response);
});
}
render(){
const posts = this.state.posts.map( post => {
return <Post title={post.title} key={post.ID} author={post.author.name} />;
});
return (
<div>
{posts}
</div>
);
}
}
export default Blog;
您的数据嵌套在 response.data
对象中。
更新
this.setState({posts: response.posts});
到
this.setState({posts: response.data.posts});
Axios returns 包含有关响应的附加信息的 HTTP 响应对象。
您遇到 asyncronous
的问题。
setState
是 async
。因此,您不会立即获得 this.state.posts
.
要解决此问题,您可以使用回调,如下所示:
this.setState({ posts: response.posts }, () => {
console.log(this.state.posts);
});
您的帖子也嵌套在 response.data
中。因此,您的 setState
应该类似于:
this.setState({ posts: response.data.posts }, () => {
console.log(this.state.posts);
});