reactjs - 尝试将响应数组映射到状态对象时出现未处理的拒绝错误
问题描述
我正在尝试编写一个非常简单的 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 {}...
我可以看到当前对象确实更新了状态,但我不知道为什么会出现此错误。
解决方案
推荐阅读
- twitter-bootstrap - 每行 5 列引导程序 4 不起作用
- r - 基于字符串的函数条件粘贴
- javascript - 如何运行现有的 react native 项目
- reactjs - 当另一个 div 位于图表上时,保持 highcharts 图例响应
- python - 如何通过之前的标签内容选择标签?
- python - 一旦遇到异常,我可以忽略下面的所有行并转到 for 循环中的另一个项目吗?
- amazon-web-services - 从 lambda 推送到 S3 或从 lambda 推送到 Kinesis Firehose 到 S3
- sql-server - SSIS 多行
- airflow - 如何读取传递给气流回填的值 --conf {"key": "value"}
- julia - 在 Julia 中将向量作为行添加到矩阵