如何在异步 api thunk 调用中传递参数

How to pass parameters in an async api thunk call

您好,我正在尝试在 redux thunk 中间件的 api 调用中为 post 方法传递参数。但这不是调用一个动作。有人可以看看代码并告诉我我在做什么错误吗:

import API from "../../_metronic/utils/api";

let FetchActions = async (id,dispatch) => {
  await API.post("companies/",id)
    .then(res => dispatch({ type: "FETCH_COMPANIES", payload: res.data }))
    .catch(err => console.log(err));
};

export default FetchActions;

我收到以下错误:

TypeError: dispatch is not a function
    at fetchAction.js:6

import API from "../../_metronic/utils/api";

let FetchActions = id => async (dispatch, getState) => {
  await API.post("companies/",id)
    .then((res) => {
      dispatch({ type: "FETCH_COMPANIES", payload: res.data })
    })
    .catch((err) => {
      console.log(err)
    });
};

export default FetchActions;

您的语法有误,因为 redux-thunk 需要方法中的 callback function 到 return。 另一件事是,如果您使用 await,则不需要 .then.catch,相反,您应该将此代码包装在 try-catch 块中。

下面的代码应该适合你。

import API from "../../_metronic/utils/api";

let FetchActions = async (id) => {
  return async (dispatch, getState) => {
      try {
       const res = await API.post("companies/",id);
       dispatch({ type: "FETCH_COMPANIES", payload: res.data })
      } catch(err) {
         console.log(err)
      }
 }
};

export default FetchActions;

阅读 redux-thunk here 中有关动作创作者的更多信息。