react children map(React报错之map() is not a function)
当我们对一个不是数组的值调用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));创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!