使用ReactJS,我有两个不同的API点,我正试图获取和重构它们:studentsscores.它们都是一组对象.

My goal is:首先,获取学生和分数,然后,将学生和分数保存在状态中,我将修改它们并基于学生和分数状态创建一个新状态.简而言之,我有3个函数:getStudentsgetScoresrearrangeStudentsAndScores.getStudentsgetScores需要在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.studentsthis.state.scores都已加载?

推荐答案

你的代码混合了continuation callbacks和promise .如果使用一种方法进行异步流控制,您会发现更容易进行推理.让我们使用promise ,因为fetch使用promise .

// Refactor getStudents and getScores to return  Promise for their response bodies
function getStudents(){
  return fetch(`api/students`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then((response) => response.json())
};

function getScores(){
  return fetch(`api/scores`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then((response) => response.json())
};

// Request both students and scores in parallel and return a Promise for both values.
// `Promise.all` returns a new Promise that resolves when all of its arguments resolve.
function getStudentsAndScores(){
  return Promise.all([getStudents(), getScores()])
}

// When this Promise resolves, both values will be available.
getStudentsAndScores()
  .then(([students, scores]) => {
    // both have loaded!
    console.log(students, scores);
  })

这种方法不仅简单,而且效率更高,因为它同时发出两个请求;你的方法是等到学生被录取后再录取分数.

Promise.all on MDN

Reactjs相关问答推荐

有关列表元素上缺少唯一键的react 错误:如何获取有关问题所在位置的更多信息?

使用useEffect挂钩获取数据

删除表2的收件箱未按预期工作

使用REACT-RUTER-V6和ZUSTANDreact 中的身份验证

在继承值更改时重置react 挂钩窗体字段值

如何在物料界面react 的多选菜单中设置最大 Select 数限制

蚂蚁 Select .列表弹出窗口不会';有时不会出现

如何使用 React 获取表单中的所有值?

React redux 工具包 useGetFilterProductsQuery 和 useGetFilterProductsByCategoriesQuery 未定义为函数

React Native - 如何处理错误带有有效负载的NAVIGATE操作..未被任何导航器处理?

部署到github pages时请求路径错误

使用 React.lazy 调试 webpack 代码拆分

Github 页面无法正确呈现 CSS,因为它是本地的

用 jest 测试包裹在 redux 和 router 中的组件

SonarCloud 代码覆盖率不适用于 Github Action

在 Reactjs 中状态发生变化时渲染一个新组件而不替换旧组件

使用 React 中的功能组件更改另一个组件的状态

在react 钩子中将数组添加到数组状态给出一个数字

仅在重新渲染后设置状态

在 redux 状态更改时更新react 按钮禁用状态