我正在从 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;
最佳答案
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);
});
关于javascript - 在axios GET请求中获取空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48481988/