我想在反应原生中使用SectionList
。
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource: [
{
title: 'New List', data: []
},
{
title: 'Old list', data: []
},
]
}
}
render() {
return (
<SectionList
style={styles.SectionContainer}
sections={this.state.dataSource}
renderSectionHeader={this._renderSectionHeader}
renderItem={this._renderItem}
keyExtractor={(item) => item.id}
/>
)
}
}
每个部分的数据都可以通过单独的URL获取,并且它们基本上具有相同的json数据:
getNewList() {
const url = website + '/api/new-list/';
return fetch(url)
.then((res) => res.json())
.catch((err) => console.log(err))
},
getOldList() {
const url = website + '/api/old-list/';
return fetch(url)
.then((res) => res.json())
.catch((err) => console.log(err))
}
如何获取和存储dataSource
SectionList
的响应数据?
答案 0 :(得分:1)
听起来你需要启动多个承诺并等待所有承诺完成。 Axios有一个很棒的.all
辅助工具,它允许你传入一组promises,然后在运行解析之前等待所有这些工作完成:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
你也可以使用本机Promise做一些接近这个的事情:
getLists(){
this.getListData().then( responses => {
this.setState({
dataSource: [
{
title: 'New List', data: responses[0]
},
{
title: 'Old list', data: responses[1]
},
]
)};
});
}
getListData(){
return new Promise( (resolve, reject) => {
let completes = 0;
let responses = [];
let url = website + '/api/new-list/';
fetch(url)
.then((res) => {
responses.push(res.json());
completes++;
if(completes === 2){
resolve(responses);
}
})
.catch((err) => console.log(err));
url = website + '/api/old-list/';
fetch(url)
.then((res) => {
responses.push(res.json());
completes++;
if(completes === 2){
resolve(responses);
}
})
.catch((err) => console.log(err))
});
}