在axios GET请求中获取空对象

伊山帕特尔

我正在从WordPress博客网站提取帖子。但是,当我控制台登录状态posts,并response.then()我得到Responseempty 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

setStateasync因此,您不会立即获得中的值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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章