注释从这开始~

总览

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

这里有个示例来展现谬误是如何产生的。

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>      {/* ️ iterate object KEYS */}      {Object.keys(employee).map((key) => {        return (          <div key={key}>            <h2>              {key}: {employee[key]}            </h2>            <hr />          </div>        );      })}      <br />      <br />      <br />      {/* ️ iterate object VALUES */}      {Object.values(employee).map((value, index) => {        return (          <div key={index}>            <h2>{value}</h2>            <hr />          </div>        );      })}    </div>  );}

咱们应用Object.keys办法失去对象的键组成的数组。

const employee = {  id: 1,  name: 'Alice',  salary: 100,};// ️ ['id', 'name', 'salary']console.log(Object.keys(employee));// ️ [1, 'Alice', 100]console.log(Object.values(employee));

咱们只能在数组上调用map()办法,所以咱们须要取得一个对象的键或者对象的值的数组。