目录总览Array.isArrayArray.fromObject.keys总览 当我们对一个不是数组的值调用map()方法时,就会产生"TypeError: map is
当我们对一个不是数组的值调用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
方法,来有条件地检查值是否为数组。
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数组。
如果有一个类数组对象,在调用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>
{}
{Object.keys(employee).map((key) => {
return (
<div key={key}>
<h2>
{key}: {employee[key]}
</h2>
<hr />
</div>
);
})}
<br />
<br />
<br />
{}
{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()
方法,所以我们需要获得一个对象的键或者对象的值的数组。
到此这篇关于React报错map() is not a function详析的文章就介绍到这了,更多相关React map is not a function内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: React报错map() is not a function详析
本文链接: https://www.lsjlt.com/news/171599.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0