使用 fetch() 获取承诺响应
Get promisse response with fetch()
我正在尝试使用 fetch()
获取我的 API 的 json 结果来获取数据,我正在使用 async/await 等待承诺解析,但是当我在 return responseJson
中的函数 fetchArticlesList()
returns 得到承诺时,像这样:Promise {_40: 0, _65: 0, _55: null, _72: null}
而不是 json。
如何在我的 <Flatlist>
组件上获得 json?
<FlatList
data={(()=> {
if (this.props.data)
return this.props.data
const response = APIRequest.fetchArticlesList()
return response
})()
}
renderItem={(article) => (
...
)}
/>
API请求:
async fetchArticlesList() {
try {
const response = await fetch(`${apiBackoffice}/articles`)
const responseJson = await response.json();
return responseJson; //this returns the promisse, instead of the json. I want to get the json
} catch (error) {
console.error(error)
}
}
APIRequest.fetchArticlesList()
是 async
函数,这就是它返回 Promise
对象的原因(查看文档 here)。将 API 响应加载到 state
中,加载后将其传递给 FlatList
。考虑以下示例
class SomeComp extends React.Component {
constructor(props) {
super(props);
this.state = { data: [], isLoading: true }
}
componentDidMount() {
APIRequest.fetchArticlesList().then(data => {
this.setState({
data,
isLoading: false
});
});
}
render() {
const { isLoading, data } = this.state;
if (isLoading) {
return <ActivityIndicator .../>
}
return (
<FlatList
data={data}
...
/>
);
}
}
希望这会有所帮助!
我正在尝试使用 fetch()
获取我的 API 的 json 结果来获取数据,我正在使用 async/await 等待承诺解析,但是当我在 return responseJson
中的函数 fetchArticlesList()
returns 得到承诺时,像这样:Promise {_40: 0, _65: 0, _55: null, _72: null}
而不是 json。
如何在我的 <Flatlist>
组件上获得 json?
<FlatList
data={(()=> {
if (this.props.data)
return this.props.data
const response = APIRequest.fetchArticlesList()
return response
})()
}
renderItem={(article) => (
...
)}
/>
API请求:
async fetchArticlesList() {
try {
const response = await fetch(`${apiBackoffice}/articles`)
const responseJson = await response.json();
return responseJson; //this returns the promisse, instead of the json. I want to get the json
} catch (error) {
console.error(error)
}
}
APIRequest.fetchArticlesList()
是 async
函数,这就是它返回 Promise
对象的原因(查看文档 here)。将 API 响应加载到 state
中,加载后将其传递给 FlatList
。考虑以下示例
class SomeComp extends React.Component {
constructor(props) {
super(props);
this.state = { data: [], isLoading: true }
}
componentDidMount() {
APIRequest.fetchArticlesList().then(data => {
this.setState({
data,
isLoading: false
});
});
}
render() {
const { isLoading, data } = this.state;
if (isLoading) {
return <ActivityIndicator .../>
}
return (
<FlatList
data={data}
...
/>
);
}
}
希望这会有所帮助!