首页 > 解决方案 > 尝试将响应数组映射到状态对象时出现未处理的拒绝错误

问题描述

我正在尝试编写一个非常简单的 React 应用程序,它将向端点发送 GET 请求,并在页面上呈现响应。响应是数组(不是 JSON)的形式,看起来像(来自 Chrome 开发工具):

h2Request.jsx:12
(3) [{…}, {…}, {…}]
    0: {requestId: 173648899, type: -89}
    1: {requestId: 1917984867, type: -89}
    2: {requestId: 2097436650, type: -89}
    length: 3
    __proto__: Array(0)

我的 React 应用程序如下所示:

import React, { Component } from "react";
import axios from "axios";
import "../App.css";

class H2Request extends Component {
  state = {
    items: this.props.value
  };

  handleClick = () => {
    axios.get("http://localhost:8003").then(response => {
      console.log(response.data);
      console.log("This object {}", this);
      this.setState({ items: response.data });
    });
  };

  render() {
    return (
      <div className="button_container">
        <button className="button" onClick={() => this.handleClick()}>
          Refresh
        </button>
        <h1>Items: {this.state.items}</h1>
      </div>
    );
  }
}

export default H2Request;

但是,我收到以下错误:

Unhandled Rejection (Error): Objects are not valid as a React child (found: object with keys {requestId, type}). If you meant to render a collection of children, use an array instead.
    in h1 (at h2Request.jsx:24)
    in div (at h2Request.jsx:20)
     in H2Request (at src/index.js:7)

▶ 25 stack frames were collapsed.

(anonymous function)
src/components/h2Request.jsx:14
  11 |   axios.get("http://localhost:8003").then(response => {
  12 |     console.log(response.data);
  13 |     console.log("This object {}", this);
> 14 |     this.setState({ items: response.data });
  15 | ^ });
  16 | };
  17 | 

通过查看我的第二个日志,This object {}...我可以看到当前对象确实更新了状态,但我不知道为什么会出现此错误。

标签: reactjsaxios

解决方案


推荐阅读