【发布时间】:2021-09-30 16:30:06
【问题描述】:
我正在尝试从 react 本机应用程序中的 url 获取部门列表
import React,{ useState,useEffect} from 'react';
import { StyleSheet, LogBox,View,Text } from 'react-native';
export default function App() {
var [department,setDepartment]=useState([])
const token = /* my token here */
const getDepartments=()=>{
const url = /*my api's url here*/
return fetch(url, {
method: 'GET',
headers: { "Authorization": "Bearer" + token ,
'Accept': 'application/json',
'Content-Type':'application/json'
}
})
.then(response => response.json())
.then(data=>console.log(data)) // returns the correct data
.catch(error => console.error(error))
}
const getdepartment = async () => {
await getDepartments().then((res) => //here lays the problem
{res.map((p, key) => {
department.push({
name: p.name,
id: p.id,
});
});
});
};
useEffect(() => {
getdepartment();
}, []);
return (
<View>
<Text>
{department[0]}
</Text>
</View>
)
}
尽管 getDepartments() 函数从 url 返回正确的数据,但 getdepartment() 函数中的 res 是未定义的
【问题讨论】:
-
如果要使用
.then,则不需要使用await,只需使用const response = await getDepartments();,然后对响应变量执行所有逻辑,所以response.map ... -
去掉
.then(data=>console.log(data))或者改成.then(data=>{ console.log(data); return data; }) -
@ponury-kostek 我都试过了..还是不行
-
你确定
res是一个数组吗?对象上不存在地图 -
我认为@skrrrt 和@ponury 的评论应该可以帮助您找出问题所在。首先,检查数据实际上是一个数组。其次,确保通过
.then(data=>{ console.log(data); return data; })返回您的promise 中的数据(注意大括号是必需的)。通过console.log但不返回任何内容,您没有从该承诺链中获得任何价值(因此undefined)
标签: javascript reactjs react-native frontend