React JS中Axios响应导出报错:TypeError: response.map is not a function
解决"TypeError: response.map is not a function"报错问题
错误原因
fetchData是异步函数,直接调用会返回Promise对象,而非API返回的数组数据。Promise对象没有map方法,因此触发该报错。
解决方案
方法1:使用async/await(推荐)
将代码包裹在异步函数中,通过await等待Promise解析为实际数据:
import { fetchData } from '../../getAllUsers' const getUsers = async () => { const response = await fetchData() // 先校验数据格式,避免API返回非数组值 if (!Array.isArray(response)) { console.log('未获取到有效用户列表') return [] } const users = response.map(item => ({ id: item.id, fullName: `${item.fname} ${item.lname}`, username: item.account.username, password: 'test', email: item.email, // 修正原代码拼写错误:emal → email role: 'admin' })) console.log(users) return users } // 执行函数 getUsers()
方法2:使用Promise.then()
通过Promise的链式调用处理异步返回的数据:
import { fetchData } from '../../getAllUsers' fetchData() .then(response => { if (!Array.isArray(response)) { console.log('未获取到有效用户列表') return [] } const users = response.map(item => ({ id: item.id, fullName: `${item.fname} ${item.lname}`, username: item.account.username, password: 'test', email: item.email, // 修正拼写错误 role: 'admin' })) console.log(users) return users })
额外提示
原代码中存在拼写错误:emal应改为email,否则生成的用户对象中该字段会缺失或错误。
内容的提问来源于stack exchange,提问作者Edmar Sanchez
相关产品推荐
相关产品推荐

