我正在从WordPress博客网站提取帖子。但是,当我控制台登录状态posts
,并response
在.then()
我得到Response
的empty object [object object]
和state
作为undefined
。
我要去哪里错了?
我也收到以下错误:
TypeError:无法读取未定义的属性“ map”
码:
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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句