拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 [Redux][Axios][React]在axios/action档案中添加redux状态

[Redux][Axios][React]在axios/action档案中添加redux状态

白鹭 - 2022-01-26 2016 0 0

当从后端接收资料时,我想添加/更改 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);
    });
};

uj5u.com热心网友回复:

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

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

uj5u.com热心网友回复:

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

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

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *