【发布时间】:2021-08-16 01:18:43
【问题描述】:
返回的 JSON 结构如下:
{
"endocrinologist": {
"en_name": "Endocrinologist",
},
"dermatologist": {
"en_name": "Dermatologist",
},
"dentis": {
"en_name": "Dentist",
},
"neurosurgeon-brain-spine": {
"en_name": "Neurosurgeon (Brain & Spine)",
},
}
我有一个服务.js 文件,我在其中获取数据并返回它,如下所示:
function getList() {
let fullURL = MY_FULL_URL
return new Promise((res, rej) => {
try {
axios.get(fullURL).then((response) => {
res(response.data)
})
} catch (error) {
rej(error)
alert(error)
}
})
}
我想根据获取的数据渲染组件的类中是这样的:
const [meds, setMeds] = useState([])
async function getMedList() {
const resp = await bookingServices.getList()
setMeds(resp)
}
useEffect(() => {
getMedList()
}, [])
...
{meds.map((s, i) =>
<MedsCard title={s.en_name} />
)}
当我运行应用程序时,我得到了
TypeError: undefined is not a function ('...meds.map...' 附近)
我尝试了一种解决方案,即将setMeds(resp) 更改为setMeds(JSON.parse(resp)),因为我得到的 JSON 是一个对象,在 o 内部我还有其他单个对象。这停止了错误,但我明白了
可能的未处理承诺拒绝 (id: 10): SyntaxError: JSON Parse 错误:意外的标识符“对象”
那么,我该如何正确解析这个 JSON?
【问题讨论】:
-
你可以在你的
getList函数中直接返回return axios.get(fullURL).then((response) => {response.data}) -
您的返回数据是 json 并且您正在使用 .map 函数,该函数只能应用于 Array
-
查看此链接以迭代对象stackoverflow.com/a/14810722/11024771
标签: javascript json react-native parsing