【问题标题】:TypeError: Cannot read property 'map' of undefined (React JS)TypeError:无法读取未定义的属性“地图”(React JS)
【发布时间】:2021-05-17 15:22:46
【问题描述】:

我正在创建一个递归函数,它应该遍历对象类型 ItemType,所以我遇到了一个错误,这个:

TypeError: Cannot read property 'map' of undefined

这是代码:

import React, { useState } from "react";

type ItemType = {
  id: Number;
  title: String;
  children: Array<Number>;
};

// Each "ItemType" element in the array have a array of children ID's. These refer
// to a ItemType.
// = This has a infinite depth.
const items: ItemType[] = [
  { id: 1, title: "Item 1", children: [2, 3, 4] },
  { id: 2, title: "Item 2", children: [1, 3, 4] },
  { id: 3, title: "Item 3", children: [1, 2, 4] },
  { id: 4, title: "Item 3", children: [1, 2, 3] }
];

function Item({ title, children }: ItemType): JSX.Element {
  const [open, toggle] = useState(false);

  // Given the children array with IDs, find each Item we refer to
  const childElements = children.map(findChild) as ItemType[];

  return (
    <div>
      <h6>
        {title} children <button onClick={() => toggle(!open)}>Open</button>
      </h6>
      <ul>
        {/* Loop children and run recursive */}
        {open &&
          childElements.map((child: ItemType) => (
            <li>
              <div>Child: {child.title}</div>
              <Item {...child} />
            </li>
          ))}
      </ul>
    </div>
  );
}

function App() {
  return (
    <div>
      {/* Start by iterating over all items */}
      {items.map(item => (
        <Item {...item} />
      ))}
    </div>
  );
}

// Function to find a Item by child id.
function findChild(childId: Number): ItemType | undefined {
  return items.find(({ id }) => id === childId);
}

export default App;

它的代码尝试遍历对象类型 ItemType 并找到每个 Item 的每个子项,当它找到一些子项时它是真的并且应该显示或者当它没有找到一些子项时是错误的,它的代码像树一样创建项目并显示在视图中,我做错了什么?

【问题讨论】:

  • 您在什么时候收到该错误?哪一行?

标签: reactjs typescript tsx


【解决方案1】:

children,包含至少一个存在于items 数组中的id。如果不是,那么children.map() 可能会返回 undefined,它将分配给childElements。在这种情况下,childElements.map 将给出错误map of undefined。因为 childElements 是未定义的并且trying to access map from undefined is not possible.

【讨论】:

    【解决方案2】:

    这是一个非常常见的错误,基本上是因为在调用map之前没有任何可空性检查,这基本上意味着您尝试使用的对象是未定义的。

    您尝试通过 Id 查找的逻辑中也可能存在错误,如果没有任何结果,则 JS 将返回 undefined,因此您需要重构代码以检查 @987654322 @ 或者如果 find 函数中没有任何结果,则默认为某个值。

    let array = [
      {
        id: 1,
        title: "Kevin",
        children: [55, 66, 23],
      },
      {
        id: 2,
        title: "Pietro",
        children: [44, 45, 13],
      },
    ];
    
    const id = array.map((i) => i.id);
    console.log(id); // This will return [1, 2]
    
    // Let's pretend for some reason we didn't get the array, it's undefined or null
    array = undefined;
    
    // Option #1: You can default to an empty array with the ?? operator.
    const id3 = (array ?? []).map((i) => i.id);
    console.log(id3);  // This will return [] (render nothing)
    
    // Option #2: You can cascade your nullability with the ? operator.
    const id4 = array?.map((i) => i.id);
    console.log(id4); // This will return undefined but won't throw.
    
    // This is your current code, it throws because there's no nulability check.
    const id2 = array.map((i) => i.id); // Cannot read property 'map' of undefined
    console.log(id2);
    

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 2017-03-26
      • 2021-09-09
      • 2020-09-16
      相关资源
      最近更新 更多