【问题标题】:React UseTable: TypeError: Cannot read properties of undefined (reading 'forEach')React UseTable:TypeError:无法读取未定义的属性(读取'forEach')
【发布时间】:2022-01-14 16:57:31
【问题描述】:

这里的快速帮助!当我尝试将数据渲染到反应表时出现上述错误。数据通过 axios 来自 api。

这里是代码

import axios from "axios";
import React, { useEffect, useState, useMemo } from "react";
import "./Modal.css";
import { useTable } from "react-table";
import { COLUMNS } from "./columns";
import "./my_style.css";
const ViewTcMapping = () => {
  const [data, setData] = useState({});

  const baseURL =
    "http://127.0.0.1:8000/api/business_process/risk_tc_mapping_details";

  useEffect(() => {
    axios
      .get(baseURL)
      .then((response) => {
        setData(response.data);
      })
      .then(
        (response) => {},
        (err) => {
          alert("No Data To Show");
        }
      )
      .catch((err) => {
        return false;
      });
  }, []);

  const columns = useMemo(() => COLUMNS, []);
  const mydata = useMemo(() => data, []);
  const tableInstance = useTable({
    columns,
    mydata,
  });

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = tableInstance;
  return (
    <div className="z-100 flex justify-center items-center">
      <div className="text-black">
        <div className="rounded overflow-hidden flex  justify-center items-center">
          <table {...getTableProps()} class="GeneratedTable">
            <thead>
              {headerGroups.map((headerGroup) => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                  {headerGroup.headers.map((column) => (
                    <th {...column.getHeaderGroupProps()}>
                      {column.render("Header")}
                    </th>
                  ))}
                </tr>
              ))}
            </thead>

            <tbody {...getTableBodyProps()}>
              {rows.map((row) => {
                prepareRow(row);
                return (
                  <tr {...row.getRowProps}>
                    {row.cells.map((cell) => {
                      return (
                        <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default ViewTcMapping;

这是包含每列标题的 COLUMNS

export const COLUMNS = [
  {
    Header: "Cost",
    accessor: "cost_category",
  },
  {
    Header: "Path",
    accessor: "path",
  },
  {
    Header: "Threat Category (PK)",
    accessor: "threat_category",
  },
  {
    Header: "Threats (ISO)",
    accessor: "threats",
  },
  {
    Header: "Asset Type",
    accessor: "asset_type",
  },
  {
    Header: "Comment",
    accessor: "comment",
  },
  {
    Header: "Operational",
    accessor: "operational",
  },
  {
    Header: "Reputational",
    accessor: "reputational",
  },
  {
    Header: "Financial",
    accessor: "financial",
  },
  {
    Header: "Health and Safety",
    accessor: "health_and_safety",
  },
  {
    Header: "Environmental",
    accessor: "environment",
  },
];

这是我要渲染到表格的 api json 数据

{
    "tc_mapping_details": [
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "Phishing",
            "threats": "Social engineering",
            "asset_type": "User",
            "comment": "Phishing by itself may not cause a breach, unless it is in combination with middle and end activities. Loss event (Breach) is calculated per exposed path that leads to the end action. For the rest, loss can be treated merely as an incident",
            "operational": "I",
            "reputational": null,
            "financial": null,
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Ransom-ware",
            "threats": "Malicious code",
            "asset_type": "Email Properties",
            "comment": "Ransomware can't launch on it own. It needs an Entry point. It needs an End point for Extortion or Breach (For example, Data Tampering or Data Compromise resp,)..",
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Malicious Software (Malware, Virus etc.)",
            "threats": "Malicious code",
            "asset_type": "Server, Network",
            "comment": "Ransomware can't launch on it own. It needs an Entry point. It needs an End point for an Attack or Breach (For example, Data Tampering or Data Compromise resp,)..",
            "operational": "I",
            "reputational": null,
            "financial": null,
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Espionage",
            "threats": "Software espionage",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": null,
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Middle",
            "threat_category": "Espionage",
            "threats": "Industrial espionage",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": "I",
            "environment": "I"
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "Web Vulnerabilities",
            "threats": "Vulnerability",
            "asset_type": "Web Properties",
            "comment": null,
            "operational": "I",
            "reputational": null,
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "Entry",
            "threat_category": "3rd Party Vulnerabilities (inc. Software)",
            "threats": "Vulnerability",
            "asset_type": null,
            "comment": null,
            "operational": "I",
            "reputational": "I",
            "financial": "I",
            "health_and_safety": null,
            "environment": null
        },
        {
            "cost_category": "Malicious Attacks",
            "path": "End",
            "threat_category": "Fraud",
            "threats": "Fraud",
            "asset_type": null,
            "comment": null,
            "operational": "B",
            "reputational": "B",
            "financial": "B",
            "health_and_safety": null,
            "environment": null
        },
       
    ]
}

我该如何解决TypeError: Cannot read properties of undefined (reading 'forEach')?

谢谢

【问题讨论】:

  • 您的代码本身没有forEach,因此错误来自您正在使用的库中的某个位置。您将需要显示更多错误堆栈,而不仅仅是错误。

标签: javascript reactjs next.js react-table


【解决方案1】:

请看,useTable 期望数组作为 data 值 (docs) 提供。您正在为它提供空对象,这是该组件的 data 的初始值。这是解决此问题的一种方法:

const [data, setData] = useState([]);

作为旁注,这些行是关于什么的并不是很清楚:

const columns = useMemo(() => COLUMNS, []);
const mydata = useMemo(() => data, []);

第一个记忆一个常数(COLUMNS),这是没有意义的。第二个在该组件的第一次运行时记住了data 的值(这是一个空数组),没有任何依赖项会触发这个记忆值的刷新。

【讨论】:

  • 这并不能修复错误。欣赏你的想法!
  • 您能分享一下您在按照我的建议应用更改后使用的确切代码吗?
【解决方案2】:

也许第一次渲染没有得到值。 您可以尝试使用条件链接“?”在你的对象之后。 赞rows?.map((row)

【讨论】:

  • 这并不能修复错误。欣赏你的想法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 2022-01-18
  • 2021-10-15
相关资源
最近更新 更多