【问题标题】:React redux Thunk - Making two ajax call one after the other with the result from the first ajax call using fetch APIReact redux Thunk - 使用 fetch API 使用第一个 ajax 调用的结果一个接一个地进行两个 ajax 调用
【发布时间】:2018-09-30 21:23:38
【问题描述】:

我正在尝试一个接一个地进行两次 ajax 调用,即,根据第一次调用数据的结果,我正在进行第二次调用。我正在尝试使用 thunk,但它没有发生,我收到错误。

actions.js

const fetchedStateNameSucess = (json) => {
    return {
      type: 'FETCH_STATE_NAME_SUCCESS',
      json
    }
}

const fetchProvidersDetailsSuccess = (providersData) => {
    return {
      type: 'FETCH_PROVIDER_DETAILS_SUCCESS',
      providersData
    }
}


export const fetchProvidersDetails = (providerId) => {
 return (dispatch) => {
  const providerUrl = `http://someUrl`;
  const stateClientCountUrl = `http://someUrl/${state}`;
  fetch(providerUrl)
  .then(response => response.json())
  .then(json => dispatch(fetchProvidersDetailsSuccess(json)))
  .then((stateValue = json[0].stateVal)
  fetch(stateClientCountUrl)
    dispatch(fetchedStateNameSucess(response)));
  };
}

在上述调用 fetch(providerUrl) 中,我在获取 stateval 的地方得到响应,如何在第二次调用以 stateval 作为参数的 fetch(stateClientCountUrl) 时使用它。

【问题讨论】:

  • 你能把确切的错误贴在这里吗?
  • 我假设您的代码中有一些拼写错误。尝试查看和编辑您的问题。您多次分派同一个动作创建者。

标签: ajax reactjs redux fetch redux-thunk


【解决方案1】:

正如Miguel 所说,您可以在.then() 子句中进行第二次查询,也可以使用async/await 语法,如下所示:

export const fetchProvidersDetails = providerId => {

 return async dispatch => {
  const providerUrl = `http://someUrl`;

  try {
       const response = await fetch(providerUrl);
       const json = await response.json();
       dispatch(fetchProvidersDetailsSuccess(json))

       const stateClientCountUrl = `http://someUrl/${json[0].stateVal}`;
       const response2 = await fetch(stateClientCountUrl);
       const json2 = await response2.json();
       dispatch(fetchedStateNameSucess(json2));
  } catch (error) {
       console.log('Error', error);
  }
}

【讨论】:

    【解决方案2】:

    如果您想将第一次调用响应中的值用于第二次 fetch 调用,则需要在第一次成功后进行第二次 fetch,或多或少像这样:

    export const fetchProvidersDetails = (providerId) => {
     return (dispatch) => {
      const providerUrl = `http://someUrl`;
      const stateClientCountUrl = `http://someUrl/${state}`;
      fetch(providerUrl)
      .then(response => response.json())
      .then(json => {
        dispatch(fetchProvidersDetailsSuccess(json));
        const stateValue = json[0].stateVal;
          fetch(stateClientCountUrl)
          .then(response => dispatch(fetchProvidersDetailsSuccess(response)));
        })
    }
    

    不要忘记在此处添加错误处理,包括 HTTP 状态代码和 JavaScript 错误(通过添加相应的 catch 子句)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多