首页 > 解决方案 > 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>
    );
  }
}

标签: javascriptreactjsaxios

解决方案


response.dataaxios是一个在请求完成时填充的对象。确实,您正在将其初始化data为一个数组,但是当您这样做时: this.setState({ data: response.data });您实际上已将其更改为一个对象。

将获得的对象解析为数组或对返回的数据执行其他操作。

编辑:在您回复后:只需执行以下操作:this.setState({data: response.data.subject});


推荐阅读