【问题标题】:Getting empty object in axios GET request在 axios GET 请求中获取空对象
【发布时间】:2018-07-07 00:15:47
【问题描述】:

我正在从 WordPress 博客网站中提取帖子。但是,当我在.then() 中控制台记录状态postsresponse 时,我得到Response 作为empty object [object object]state 作为undefined

我哪里错了?

我也收到以下错误:

TypeError: 无法读取未定义的属性“地图”

代码:

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;

【问题讨论】:

  • 当你设置state是posts一个空的或者未定义的数组?
  • 只是console.log响应... axios响应返回对象数据键中的数据。
  • 当我只返回responseconsole.log 仍然给我empty object 但这次我的状态值也为empty object

标签: javascript reactjs get typeerror axios


【解决方案1】:

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);
});

【讨论】:

    【解决方案2】:

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

    更新

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 2022-11-01
      • 2020-10-14
      • 2018-01-06
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多