Javascript react-native async 函数返回promise 但不返回我的json 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45200723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
react-native async function returns promise but not my json data?
提问by tempomax
I'm learning react-native, and I'm running into an issue. Why does getting data on return from an async function return a promise, but in the async function itself, it correctly returns an array of objects?
我正在学习 react-native,但遇到了一个问题。为什么从异步函数获取数据返回一个承诺,但在异步函数本身中,它正确返回一个对象数组?
On componentDidMount(), I call my async function which in turn does a fetch to an api url:
在 上componentDidMount(),我调用我的异步函数,该函数反过来获取 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;
}
In console.log(json), I get the correct list of json objects, and I can access them with json[0].name. But later, console.log(data)returns a promise with odd data:
在 中console.log(json),我获得了正确的 json 对象列表,并且可以使用json[0].name. 但后来,console.log(data)返回一个带有奇数数据的承诺:
Promise {_40: 0, _65: 0, _55: null, _72: null}
... and I can no longer find my json objects. Why is this? More importantly, how can I retrieve my json data in componentDidMount()so that I can set it as the dataSource?
...我再也找不到我的 json 对象了。为什么是这样?更重要的是,我如何检索我的 json 数据componentDidMount()以便我可以将其设置为dataSource?
回答by Anthony Ngene
Since getData()is a promise, you should be able to obtain the data in a thenblock as follows:
由于getData()是承诺,您应该能够then按如下方式获取块中的数据:
componentDidMount() {
this.getData()
.then((data) => {
this.setState({
dataSource:this.state.dataSource.cloneWithRows(data),
})
});
}
回答by itinance
Another approach similar to the original code of the questioner:
另一种类似于提问者原始代码的方法:
async componentDidMount() {
let data = await this.getData();
console.log(data);
this.setState({
dataSource:this.state.dataSource.cloneWithRows(data),
})
}
回答by Cristian Canales
Or another way is
或者另一种方式是
async componentDidMount() {
const { data: dataSource = [] } = await this.getData();
this.setState({dataSource})
}
This will copy your data to a inmutable object an reasign the name, also, set a default value to the object dataSource
这会将您的数据复制到不可变对象并重新指定名称,并为该对象设置默认值 dataSource

