![](/img/trans.png)
[英]React Native Unhandled promise rejection | React-Native, Async,
[英]react-native async function returns promise but not my json data?
我正在學習 react-native,但遇到了一個問題。 為什么從異步函數獲取數據返回一個承諾,但在異步函數本身中,它正確返回一個對象數組?
在componentDidMount()
,我調用我的 async 函數,該函數反過來獲取一個 api url:
componentDidMount() {
let data = this.getData();
console.log(data); // <-- Promise {_40: 0, _65: 0, _55: null, _72: null}
this.setState({
dataSource:this.state.dataSource.cloneWithRows(data),
})
}
async getData() {
const response = await fetch("http://10.0.2.2:3000/users", {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
const json = await response.json();
console.log(json); // <-- (5) [Object, Object, Object, Object, Object]
return json;
}
在console.log(json)
,我得到了正確的 json 對象列表,我可以使用json[0].name
訪問它們。 但后來, console.log(data)
返回一個帶有奇數數據的承諾:
Promise {_40: 0, _65: 0, _55: null, _72: null}
...我再也找不到我的 json 對象了。 這是為什么? 更重要的是,如何在componentDidMount()
檢索我的 json 數據,以便將其設置為dataSource
?
由於getData()
是一個承諾,您應該能夠在then
塊中獲取數據,如下所示:
componentDidMount() {
this.getData()
.then((data) => {
this.setState({
dataSource:this.state.dataSource.cloneWithRows(data),
})
});
}
另一種類似於提問者原始代碼的方法:
async componentDidMount() {
let data = await this.getData();
console.log(data);
this.setState({
dataSource:this.state.dataSource.cloneWithRows(data),
})
}
或者另一種方式是
async componentDidMount() {
const { data: dataSource = [] } = await this.getData();
this.setState({dataSource})
}
這會將您的數據復制到不可變對象並重新指定名稱,還將默認值設置為對象dataSource
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.