目录
  • 总览
  • Array.isArray
  • Array.from
  • Object.keys

总览

当我们对一个不是数组的值调用map()方法时,就会产生"TypeError: map is not a function"错误。为了解决该错误,请将你调用map()方法的值记录在console.log上,并确保只对有效的数组调用map

React报错map() is not a function详析

这里有个示例来展示错误是如何发生的。

const App = () => {
  const obj = {};
  // ⛔️ Uncaught TypeError: map is not a function
  return (
    <div>
      {obj.map(element => {
        return <h2>{element}</h2>;
      })}
    </div>
  );
};
export default App;

我们在一个对象上调用Array.map()方法,得到了错误反馈。

为了解决该错误,请console.log你调用map方法的值,确保它是一个有效的数组。

export default function App() {
  const arr = ['one', 'two', 'three'];
  return (
    <div>
      {arr.map((element, index) => {
        return (
          <div key={index}>
            <h2>{element}</h2>
          </div>
        );
      })}
    </div>
  );
}

Array.isArray

你可以通过使用Array.isArray方法,来有条件地检查值是否为数组。

const App = () => {
  const obj = {};
  return (
    <div>
      {Array.isArray(obj)
        ? obj.map(element => {
            return <h2>{element}</h2>;
          })
        : null}
    </div>
  );
};
export default App;

如果值为数组,则返回对其调用map方法的结果,否则返回null。这种方式不会得到错误,即使值不是一个数组。

如果值是从远程服务中获取,请确保它是你期望的类型,将其记录到控制台,并确保你在调用map方法之前将其解析为一个原生JavaScript数组。

Array.from

如果有一个类数组对象,在调用map方法之前你尝试转换为数组,可以使用Array.from()方法。

const App = () => {
const set = new Set(['one', 'two', 'three']);
return (
  <div>
    {Array.from(set).map(element => {
      return (
        <div key={element}>
          <h2>{element}</h2>
        </div>
      );
    })}
  </div>
);
};
export default App;

在调用map方法之前,我们将值转换为数组。这也适用于类数组的对象,比如调用getElementsByClassName方法返回的NodeList

Object.keys

如果你尝试迭代遍历对象,使用Object.keys()方法获取对象的键组成的数组,在该数组上可以调用map()方法。

export default function App() {
const employee = {
id: 1,
name: 'Alice',
salary: 100,
};
return (
<div>
{/*

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。