我试图通过从 React Native App 获取来调用 API,但由于某种原因它没有记录响应数据 (console.warn('data', data))。它打印“调用 getArtists”日志,但没有任何反应。
const URL = 'https://jsonplaceholder.typicode.com/posts'
function getArtists(){
console.log('call to getArtists')
return fetch(URL)
.then(response => response.json())
.then(data => {
console.warn('data', data)
})
}
代码可在此处获得:https : //snack.expo.io/rkzea2Zlm at components/api-client.js
我究竟做错了什么?
首先在你的“api_client.js”中,像下面的代码一样在里面放一个返回值。
function getArtists(){
console.log('call to getArtists')
return fetch(URL)
.then(response => response.json())
.then(data => {
return data
})
}
在您的 App.js 中,只需在 componentWillMount 中执行此操作。
componentDidMount(){
getArtists()
.then(data => {
alert(JSON.stringify(data))
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句