【问题标题】:[Redux][Axios][React] Adding redux state inside of a axios / action file[Redux][Axios][React] 在 axios / action 文件中添加 redux 状态
【发布时间】:2022-01-27 03:38:59
【问题描述】:

我想在从后端接收数据时添加/更改 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);
    });
};

【问题讨论】:

  • 告诉我 getCouriers 呼叫的线路

标签: javascript reactjs redux axios


【解决方案1】:

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

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

【讨论】:

  • 我无法使用确切的代码使其工作。我收到一条错误消息,说我不能将它与类组件一起使用。但是,由于您的回答对我有所帮助,我接受了答案。谢谢!
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    @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);
        });
    };
    

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2020-10-10
      • 2018-09-27
      • 2018-11-14
      相关资源
      最近更新 更多