【发布时间】:2021-07-23 18:27:14
【问题描述】:
我正在尝试从 React Native 应用程序中的 URL 获取部门列表
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())
.catch(error => console.error(error))
}
const getdepartment = async () => {
await getDepartments().then((res) => {
console.log('res',res)
res.map((p, key) => {
setDepartment([...department,department.push({
name: p.name,
id: p.id,
})])
});
});
console.log(department[0].name) //displays the correct value
};
return (
<View>
<Button
onPress={()=>getdepartment()}
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
<Text>{department[0].name}</Text> //here lays the problem
</View>
)
}
尽管 getdepartment() 函数返回正确的部门 [0],但 JSX 中的部门 [0] 未定义
【问题讨论】:
标签: javascript reactjs react-native jsx