[Redux][Axios][React] 在 axios / action 文件中添加 redux 状态

[Redux][Axios][React] Adding redux state inside of a axios / action file

我想 add/change 从后端接收数据时的 redux 状态。此状态控制加载微调器。 下面的代码是我认为应该有效的。

我错过了什么?

CouriersActions.js

import axios from "axios";
import { toastOnError } from "../../utils/Utils";
import { GET_COURIERS, ADD_STATE_LOADING } from "./CouriersTypes";

export const addStateLoading = (state_loading) => ({
  type: ADD_STATE_LOADING,
  state_loading,
});

export const getCouriers = () => dispatch => {
  var tempx = {show: true};
  addStateLoading(tempx);
  axios
    .get("/api/v1/couriers/")
    .then(response => {
      dispatch({
        type: GET_COURIERS,
        payload: response.data
      });
      var tempx = {show: false};
      addStateLoading(tempx);
    })
    .catch(error => {
      toastOnError(error);
    });
};

解决此类问题的一种简单方法,为所有服务以及您需要的地方创建自定义挂钩。

export const useCouriers = () => {
  const dispatch = useDispatch();
  const getCouriers = async () => {
    try {
      dispatch(addStateLoading({ show: true }));
      const response = await axios.get("/api/v1/couriers/");
      dispatch({
        type: GET_COURIERS,
        payload: response.data,
        // I think this should be response.data.data
      });
    } catch (error) {
      toastOnError(error);
    } finally {
      dispatch(addStateLoading({ show: false }));
    }
  };
  return { getCouriers };
};

内部组件

const { getCouriers } = useCouriers();
// call where you need

如果你想使用redux,查看redux-toolkit,它对redux的开发有很大帮助。

https://redux-toolkit.js.org/

@rahul-sharma 的回答帮助我找到了这个答案。我刚刚在 dispatch 中调用了 addStateLoading。

CouriersActions.js

import axios from "axios";
import { toastOnError } from "../../utils/Utils";
import { GET_COURIERS, ADD_STATE_LOADING } from "./CouriersTypes";

export const addStateLoading = (state_loading) => ({
  type: ADD_STATE_LOADING,
  state_loading,
});

export const getCouriers = () => dispatch => {
  var tempx = {show: true};
  addStateLoading(tempx);
  axios
    .get("/api/v1/couriers/")
    .then(response => {
      dispatch({
        type: GET_COURIERS,
        payload: response.data
      });
      dispatch(addStateLoading({ show: false }));
    })
    .catch(error => {
      toastOnError(error);
    });
};