javascript - React:如何修复“未捕获的 TypeError:this.state.data.map 不是函数”
问题描述
我收到“未捕获的 TypeError:this.state.data.map 不是函数”错误,即使我可以成功地将数据从 API 记录到控制台。我发现了类似的问题,但是还没有提出一个好的解决方案来解决这个问题。
我在这里读到,“JavaScript 中的对象 {} 没有方法 .map(),它仅适用于数组 []。” 但是,我不知道如何解决这个问题,迭代一个对象并将数据检索到 React 前端。谢谢你,任何帮助将不胜感激。
import React, { Component } from "react";
import axios from "axios";
export default class GetSubjects extends Component {
constructor(props) {
super(props);
this.getsubjects = this.getsubjects.bind(this);
this.onSearch = this.onSearch.bind(this);
this.state = {
keyword: "",
data: []
};
}
getsubjects(e) {
this.setState({ keyword: e.target.value });
}
onSearch(e) {
e.preventDefault();
const searchsub = {
keyword: this.state.keyword
};
axios
.get(`http://localhost:3000/api/messages/courses/${this.state.keyword}`)
.then(response => {
console.log(response);
this.setState({
data: response.data
});
});
console.log(this.state.keyword);
console.log(this.state.data);
}
componentDidMount() {}
render() {
return (
<div>
<br />
<div>
<label>Course Name</label>{" "}
<input
placeholder="Enter Course Name"
type="text"
value={this.state.keyword}
onChange={this.getsubjects}
name="keyword"
required
/>{" "}
<button className="btn btn-primary" onClick={this.onSearch}>
Get Subjects
</button>
</div>
<br />
<table className="table table-bordered">
<thead>
<tr>
<th scope="col">Course Name</th>
<th scope="col">Subjects</th>
</tr>
</thead>
<tbody>
{this.state.data.map(function(subject) {
return (
<tr>
{" "}
<td key={subject.id}>{subject.name}</td>{" "}
<td key={subject.id}>{subject.subjects}</td>{" "}
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}
解决方案
response.data
axios
是一个在请求完成时填充的对象。确实,您正在将其初始化data
为一个数组,但是当您这样做时:
this.setState({ data: response.data });
您实际上已将其更改为一个对象。
将获得的对象解析为数组或对返回的数据执行其他操作。
编辑:在您回复后:只需执行以下操作:this.setState({data: response.data.subject});
推荐阅读
- visual-studio-code - Visual Studio Code 在保存时随机开始展开全部
- flutter - 如何在特定容器/小部件上将 resizeToAvoidBottomInset 应用于 false,而不是整个应用程序?
- pylint - 为什么pylint在“return”(no-else-return)之后抱怨不必要的“elif”?
- node.js - 为什么 vscode 在 typescript monorepo 的包内没有智能感知功能?
- javascript - 使用数组的目的地城市
- ios - iOS 出现 Flutter Workmanager 插件实现缺失错误
- python-3.x - 迁移命令后,Django 自动创建 sqlite3 但不会自动创建 postgresql 数据库
- google-api - Google API:People 与 PeopleService
- postgresql - PostgreSQL 过程
- c - 无法运行此 C 代码:没有错误或警告,但程序只是崩溃