首页 > 解决方案 > React 异步动作调度

问题描述

在我的反应应用程序中,我遇到了异步等待操作的问题。

这是我的代码。

    export const createOrUpdateProfile = (profileData, history) => async dispatch => {
  try {
    dispatch(setProfileLoading());         
    await axios.post('/api/profile', profileData);
    history.push('/dashboard');
  } catch(error) {
    dispatch(profileError(GET_ERRORS, error.response.data));
  }
}

问题是加载微调器在短暂延迟后显示。我用 . 将loading(a bool) 设置为 true setProfileLoading()。加载仪表板时,仅基于profileLoading布尔值显示微调器。

但在导航到仪表板之前,会调度一个异步操作来创建配置文件:

await axios.post('/api/profile', profileData);

然后只发生导航:

history.push('/dashboard');

为了克服这个问题,我将history.push('/dashboard')调用放在异步操作之前。我这样做对吗?在进行 API 调用之前进行导航似乎有点奇怪。有人可以帮我吗?

export const createOrUpdateProfile = (profileData, history) => async dispatch => {
  try {
    dispatch(setProfileLoading());
    history.push('/dashboard');
    await axios.post('/api/profile', profileData);
  } catch(error) {
    dispatch(profileError(GET_ERRORS, error.response.data));
  }
}

标签: reactjs

解决方案


推荐阅读