【问题标题】:How to fix "TypeError: Cannot read property 'map' of undefined" in JavaScript?如何修复 JavaScript 中的“TypeError:无法读取未定义的属性'map'”?
【发布时间】:2019-11-05 14:23:51
【问题描述】:

我正在从 API 获取数据,然后将其映射到表格中。但是提取不起作用,加载页面时状态保持未定义。尽管 API 工作正常并正确发送数据,但我在 Postman 和浏览器上都检查了它。 如何解决这个问题?

页面崩溃了,我用 Google 搜索了一下,并添加了条件渲染来阻止它崩溃。但仍然无法解决获取数据和映射数据的问题。

这是不工作页面的代码:

import React, { Component } from "react";
import fetch from "isomorphic-unfetch";

export default class extends Component {
  static async getInitialProps() {
    const res = await fetch("https://linktoapi/path");
    const studentData = await res.json();
    return studentData;
  }
  componentWillMount() {
    this.setState({
      studentData: this.props.studentData
    });
  }

  render() {
    return (
      <table className="table is-striped is-fullwidth has-text-centered">
        <thead>
          <tr>
            <th>Name</th>
            <th>Class</th>
            <th>Section</th>
            <th>Batch</th>
            <th>Contact No.</th>
          </tr>
        </thead>
        <tbody>
          {this.state.studentData && this.state.studentData.map(studentDataRow => (
            <tr id={studentDataRow._id}>
              <td>{studentDataRow.name}</td>
              <td>{studentDataRow.class}</td>
              <td>{studentDataRow.section}</td>
              <td>{studentDataRow.batch}</td>
              <td>{studentDataRow.contact_no}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
}

这是来自 API 的数据:

[{"_id":"5d0cd67416c3a60017608a48","type":"student","name":"Samnan","contact_no":"9999","class":"123","section":"av","batch":"2002","__v":0},
{"_id":"5d0d1a7bfe72ac001775d778","type":"student","name":"as","contact_no":"0","class":"d","section":"r","batch":"a","__v":0},
{"_id":"5d0d1b24fe72ac001775d779","type":"student","name":"ab","contact_no":"0","class":"d","section":"afrgr","batch":"adsda","__v":0},
{"_id":"5d0d1b58259c5d6cd69acf3b","type":"student","name":"akash","contact_no":"567","class":"23","section":"h","batch":"2012","__v":0},
{"_id":"5d0ea1eb91eac20017f36739","type":"student","name":"as","contact_no":"08109209","class":"v","section":"qere","batch":"re","__v":0}]

要在本地重现此问题:

git clone https://github.com/Geektrovert/EduSys.git && cd EduSys
npm i
npm run dev

然后转到http://localhost:3000/students

【问题讨论】:

  • 尚未测试,但是:id={studentDataRow.id_} 你有一个错字。应该是id={studentDataRow._id)}
  • @Oli 改了,但还是不行

标签: javascript reactjs mapping next.js


【解决方案1】:

我改变了一些东西让它运行。 getInitialProps 似乎没有被调用。我将您的 API 调用移至 componentDidMount 并使用状态来存储学生数据。

import React, { Component } from "react";
import fetch from "isomorphic-unfetch";

export default class extends Component {

  constructor(props) {
    super(props);

    this.state = {
      studentData: []
    };
  }

  async componentDidMount() {
    const res = await fetch("https://edusys-yas.herokuapp.com/api/students");
    const studentData = await res.json();

    this.setState({ studentData });
  }
  render() {
    return (
      <table className="table is-striped is-narrow is-fullwidth">
        <thead>
          <tr>
            <th>Name</th>
            <th>Class</th>
            <th>Section</th>
            <th>Batch</th>
            <th>Contact No.</th>
          </tr>
        </thead>
        <tbody>
          {this.state.studentData.map(studentDataRow => (
            <tr>
              <td>{studentDataRow.name}</td>
              <td>{studentDataRow.class}</td>
              <td>{studentDataRow.section}</td>
              <td>{studentDataRow.batch}</td>
              <td>{studentDataRow.contact_no}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
}

【讨论】:

  • NextJS Docs > getInitialProps 不能在子组件中使用。仅在页面中。
  • 此方法有效,但不会从 SSR 返回,仅从 CSR 返回。如果这对您来说是个问题,请将getInitialProps 移至students.js 页面,并将其作为道具传递给StudentTable.js
  • 感谢您的信息,我会记住这些@Oli
猜你喜欢
  • 2019-08-19
  • 2021-10-03
  • 2021-10-28
  • 2019-11-27
  • 2022-01-12
  • 2022-11-22
  • 2023-01-19
  • 2019-12-08
  • 1970-01-01
相关资源
最近更新 更多