Redux-Toolkit中间件中的Axios调用陷入死循环

k97glaaz  于 2023-05-07  发布在  iOS
关注(0)|答案(1)|浏览(215)

在我的react项目中,我有redux-toolkit用于状态管理,我使用一个中间件函数在发送到reducer之前对有效负载进行更改。在中间件文件中,我正在执行一个API调用,将文本更改为ES,但由于Api中的错误,该中间件函数进入了无限循环。你可以在下面的代码片段中看到中间件函数和API调用代码。

import { getSpanishText } from "../../helpers/storeSpanishText";

export const kioskSettingsMiddleware = (store) => (next) => async (action) => {
    const actionType = action.type;
    if (actionType === "kisokSettings/saveKioskPortalSettings") {
      const prevState = store.getState().kioskSettings;
      const data = action.payload;
      let settingObject = {
        autoDisconnect: data.auto_hang_up_call,
        multiPMS: data?.is_multi_pms_mapping,
      };

    if (
      data?.is_complete_operation_message &&
      data?.complete_operation_message !== prevState?.completeMessage
    ) {
      settingObject["completeMessage"] = data?.complete_operation_message;
      settingObject["EScompleteMessage"] = await getSpanishText(
        "EScompleteMessage",
        data?.complete_operation_message
      );
    }
   
    return store.dispatch({ type: actionType, payload: settingObject });
  }
  return next(action);
}

下面是API调用代码

export const getSpanishText = (key, msg) => {
  return axios
    .get(`https://translation.googleapis.com/language/translate/v2`, {
      params: {
        key: TRANSLATE_API_KEY,
        q: msg,
        target: "es",
      },
    })
    .then((res) => {
      if (res.status === 200) {
        ipcRenderer.send("logs", {
          type: "info",
          msg: `ES TRANSLATION- [${key} : ${res.data.data.translations[0].translatedText}]`,
        });
        return res.data.data.translations[0].translatedText;
      }
    })
    .catch((err) => {
      ipcRenderer.send("logs", {
        type: "info",
        msg: `FALLBACK EN - [${key} : ${msg}]`,
      });
      return msg;
    });
};
syqv5f0l

syqv5f0l1#

你的

return store.dispatch({ type: actionType, payload: settingObject });

使用相同的操作类型启动一个新的分派-因此它将再次运行到相同的中间件中。
也许你想打电话

return next({ type: actionType, payload: settingObject })

而不是

相关问题