使用ReactJS,我有两个不同的API点,我正试图获取和重构它们:students
和scores
.它们都是一组对象.
My goal is:首先,获取学生和分数,然后,将学生和分数保存在状态中,我将修改它们并基于学生和分数状态创建一个新状态.简而言之,我有3个函数:getStudents
、getScores
和rearrangeStudentsAndScores
.getStudents
和getScores
需要在rearrangeStudentsAndScores
运行之前完成.
My problem is:有时rearrangeStudentsAndScores
会在getScores
完成之前运行.这把rearrangeStudentsAndScores
人搞砸了.但有时它会完成.我不知道为什么它在50%的时间里有效,但我需要让它在rearrangeStudentsAndScores
%的时间里有效.
这是我必须在Client
文件中填写的fetch
students and scores
:
function getStudents(cb){
return fetch(`api/students`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then((response) => response.json())
.then(cb)
};
function getScores(cb){
return fetch(`api/scores`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then((response) => response.json())
.then(cb)
};
然后我把它们结合在一起:
function getStudentsAndScores(cbStudent, cbScores, cbStudentsScores){
getStudents(cbStudent).then(getScores(cbScores)).then(cbStudentsScores);
}
在我的react应用程序中,我有以下内容:
getStudentsAndScores(){
Client.getStudentsAndScores(
(students) => {this.setState({students})},
(scores) => {this.setState({scores})},
this.rearrangeStudentsWithScores
)
}
rearrangeStudentsWithScores(){
console.log('hello rearrange!')
console.log('students:')
console.log(this.state.students);
console.log('scores:');
console.log(this.state.scores); //this returns [] half of the time
if (this.state.students.length > 0){
const studentsScores = {};
const students = this.state.students;
const scores = this.state.scores;
...
}
}
不知何故,当我达到rearrangeStudentsWithScores
时,this.state.scores
仍然是[]
.
在运行rearrangeStudentsWithScores
之前,如何确保this.state.students
和this.state.scores
都已加载?