【问题标题】:How to create playload in createAsyncThunk when using axios使用axios时如何在createAsyncThunk中创建payload
【发布时间】:2020-12-18 07:07:01
【问题描述】:

我开始学习 redux,并且有一个动作创建者 (createAsyncThunk) 用于执行异步任务,我正在尝试在其中使用 axios,就像这样

export const loginUser = createAsyncThunk(
  "auth/login",
  (authData) => {
    return axios.post("auth/token/login/", {
      email: authData.email,
      password: authData.password,
    });
  },
  {
    condition: (authData, { getState, extra }) => {
      const { auth } = getState();
      if (["fulfilled", "loading"].includes(auth.status)) {
        return false;
      }
    },
  }
);

这可行,但我明白了

index.js:1 A non-serializable value was detected in an action, in the path: `payload.config.transformRequest.0`. Value: ƒ transformRequest(data, headers) {
    normalizeHeaderName(headers, 'Accept');
    normalizeHeaderName(headers, 'Content-Type');

    if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.i… 
Take a look at the logic that dispatched this action:  {type: "auth/login/fulfilled", payload: {…}, meta: {…}} 
(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants) 
(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)

这是由于有效负载,这意味着我不应该在 payloadCreator 中返回 doc 中的 axios 他们使用 async/await 仅返回结果,但在 axios doc 中提到

注意:async/await 是 ECMAScript 2017 的一部分,在 Internet Explorer 和旧版浏览器中不受支持,因此请谨慎使用。

那么我将如何解决这个问题以及我应该如何在createAsyncThunk 中调用 axios

【问题讨论】:

    标签: javascript redux axios redux-thunk redux-toolkit


    【解决方案1】:

    axios.post() 返回一个 Axios response 对象。您需要返回 response.data 字段:

    export const loginUser = createAsyncThunk(
      "auth/login",
      async (authData) => {
        const response = axios.post("auth/token/login/", {
          email: authData.email,
          password: authData.password,
        });
        return response.data;
      },
      {
        condition: (authData, { getState, extra }) => {
          const { auth } = getState();
          if (["fulfilled", "loading"].includes(auth.status)) {
            return false;
          }
        },
      }
    );
    

    【讨论】:

    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2020-09-23
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2022-09-28
    相关资源
    最近更新 更多