[英][Redux][Axios][React] Adding redux state inside of a axios / action file
I want to add/change a redux state when the data is received from the backend.当从后端接收到数据时,我想添加/更改 redux state。 This state controls a loading spinner.
这个 state 控制加载微调器。 The code below is what I thought that should work.
下面的代码是我认为应该可以工作的。
What am I missing?我错过了什么?
CouriersActions.js 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);
});
};
A simple way of solving this kind issue, create custom hook for all services and where ever you need it.解决此类问题的一种简单方法是为所有服务以及您需要的任何地方创建自定义挂钩。
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 };
};
Inside component内部组件
const { getCouriers } = useCouriers();
// call where you need
If you want to use redux, check redux-toolkit, it helps a lot the development with redux.如果你想使用 redux,请查看 redux-toolkit,它对使用 redux 的开发有很大帮助。
@rahul-sharma answer helped me to find this answer. @rahul-sharma 的回答帮助我找到了这个答案。 I just called addStateLoading inside of dispatch.
我刚刚在调度中调用了 addStateLoading。
CouriersActions.js 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);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.