代码之家  ›  专栏  ›  技术社区  ›  Ishan Patel

在axios GET请求中获取空对象

  •  3
  • Ishan Patel  · 技术社区  · 6 年前

    我正在从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;
    
    2 回复  |  直到 5 年前
        1
  •  2
  •   Vishal    6 年前

    您对 asyncronous .

    setState async . 因此,您不会立即获得 this.state.posts .

    要解决此问题,可以按如下方式使用回调:

    this.setState({ posts: response.posts }, () => {
        console.log(this.state.posts);
    });
    

    您的帖子也嵌套在 response.data . 那么,你的 设置状态 应该看起来像:

    this.setState({ posts: response.data.posts }, () => {
        console.log(this.state.posts);
    });
    
        2
  •  1
  •   JerguÅ¡ Lejko    6 年前

    您的数据嵌套在 response.data 对象

    使现代化

    this.setState({posts: response.posts});
    

    this.setState({posts: response.data.posts});
    

    Axios返回一个HTTP响应对象,该对象包含有关响应的其他信息。