解决 React 中 Uncaught TypeError: map() is not a function 错误
当我们在一个不是数组的值上调用 map()
方法时,会产生“TypeError: map is not a function” 错误。 要解决该错误,需要 console.log
记录我们正在调用 map() 方法的值,并确保仅在有效数组上调用 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
方法有条件地检查值是否为数组。
const App = () => {
const obj = {};
return (
<div>
{Array.isArray(obj)
? obj.map(element => {
return <h2>{element}</h2>;
})
: null}
</div>
);
};
export default App;
我们使用了一个三元运算符,它与 if/else 语句非常相似。
如果值是一个数组,我们返回调用它的map方法的结果,否则我们返回null。 这样,即使值不是数组,我们也不会收到错误消息。
如果该值是从远程服务器获取的,请通过将其记录到控制台来确保它是我们期望的类型,并确保在调用其上的 map 方法之前已将其解析为原生 JavaScript 数组。
如果我们有一个类似数组的对象,并且在调用 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()
方法获取对象键的数组,我们可以在该数组上调用 map() 方法。
export default function App() {
const employee = {
id: 1,
name: 'Alice',
salary: 100,
};
return (
<div>
{/* ?️ 迭代对象的 KEYS */}
{Object.keys(employee).map((key) => {
return (
<div key={key}>
<h2>
{key}: {employee[key]}
</h2>
<hr />
</div>
);
})}
<br />
<br />
<br />
{/* ?️ 迭代对象的 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() 方法,因此我们需要获取对象键的数组或对象的值。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。