反应原生api呼叫响应

时间:2018-04-18 14:43:44

标签: javascript json react-native

我正在发出一个http呼叫请求,由于某种原因,响应非常奇怪!

我的电话如下:

      getOne: id => {
            return axios.get('posts/1', {
                params: {
                    id: id
                }
            }).then(function (response) {
                return response;
            }).catch(function (error) {
                if (error.response) {
                    // The request was made and the server responded with a status code
                    return error;
                } else if (error.request) {
                    // The request was made but no response was received
                    return error.request;
                } else {
                    // Something happened in setting up the request that triggered an Error
                    return error.message;
                }
            });
        },

从组件我称之为

categoryApi.getOne(1).then(response => {
            if (response.data) {
                this.setState({isLoading: false});
                console.log(response.data);
                this.setState({categories: this.state.categories.push(response.data)});
                console.log(this.state.categories);
            } else {
                this.setState({isLoading: false});
                Alert.alert(
                    'Something wrong happened!',
                    'My Alert Msg',
                    [],
                    {cancelable: true}
                )
            }
        });

在控制台中,响应看起来像:

     Object {
      "body": "quia et suscipit
       suscipit recusandae consequuntur expedita et cum
       reprehenderit molestiae ut ut quas totam
       nostrum rerum est autem sunt rem eveniet architecto",
       "id": 1,
       "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
       "userId": 1,
     }

问题在于我希望响应像对象一样:

{
          "body": "quia et suscipit
           suscipit recusandae consequuntur expedita et cum
           reprehenderit molestiae ut ut quas totam
           nostrum rerum est autem sunt rem eveniet architecto",
           "id": 1,
           "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
           "userId": 1,
         }

我需要更改什么,所以我没有Object {}而只有{}

1 个答案:

答案 0 :(得分:1)

尝试在JS控制台中输入:

var myObject = {a: 1, b: 2}

然后检查你的新对象:

myObject

它应该显示为:

Object { a: 1, b: 2 }

{}Object{}都是一回事。后者是控制台选择显示JavaScript对象的方式,因为它们具有与之关联的其他数据,如果单击以展开对象,则可以看到这些数据:

{...} a: 1 b: 2 __proto__: Object {...}

查看本教程中的working with objects