我试图找到进行此服务调用的最佳方法,将所有数据保留在一个对象中。调用返回一个对象,如果有下一页,该对象也返回一个URL我递归地调用此下一个URL,直到它为null。当前,并非所有电话都能解决,所以我无法获取所有数据
componentDidMount() {
waniKaniAxios.get('/subjects?types=vocabulary')
.then(response => {
console.log(response.data);
let wkObjectSorted = this.traverseWaniKaniVocab(response.data)
console.log(wkObjectSorted);
})
.catch(error => {
console.log('something broke', error);
});
}
traverseWaniKaniVocab = (object) => {
let result = {};
object.data.forEach(vocab => {
//checking to see if there is an object with the same level as the vocab.
let foundLevelObject = result[vocab.data.level];
let vocabObject = {
id: vocab.id,
value: vocab.data.characters,
meanings: vocab.data.meanings.map(({meaning}) => meaning),
partsOfSpeach: vocab.data.parts_of_speech,
readings: vocab.data.readings.map(({reading}) => reading),
selected: false
};
//If there is then it adds the vocab to the array list of vocab for that level,
//otherwise it creates a new level and creates array of vocab in that level and add vocab to that array
if(foundLevelObject) {
result[vocab.data.level].vocabList.push(vocabObject);
} else {
let levelObject = {
level: vocab.data.level,
vocabList: [vocabObject],
accordionOpen: false
};
result[vocab.data.level] = levelObject;
}
});
//if object has next page url then it calls that url
if(object.pages.next_url) {
waniKaniAxios.get(object.pages.next_url.replace(waniKaniAxios.defaults.baseURL, ''))
.then(response => {
//calls this function again
let nextPageObject = this.traverseWaniKaniVocab(response.data);
//it takes what is returned from that function call and combines the two objects
Object.keys(nextPageObject).map((key => {
//if key already exits in results it combies both arrays together and saves that new array into the key
//otherwise if the key doesn't exist in result it takes the whole value key in nextPageObject and saves
//into result
if(result[key]) {
result[key].vocabList = [...result[key].vocabList,...nextPageObject[key].vocabList];
} else {
result[key] = nextPageObject[key];
}
}));
})
.catch(error => {
console.log('something broke', error);
});
}
return result;
}
抽象出wanikaniaxios.get另一个函数以使递归更加清晰。