當從后端接收資料時,我想添加/更改 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/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395764.html
標籤:javascript 反应 还原 公理
上一篇:帶反斜杠的字串到字典
下一篇:動態填充物件以回應陣列中的值
