那么,您可以在现有的操作列表中添加另外两个操作。一种用于获取 API 调用开始的状态,另一种用于获取任何错误。有点像这样:
import * as types from "./actionTypes";
export function beginApiCall() {
return { type: types.BEGIN_API_CALL };
}
export function apiCallError() {
return { type: types.API_CALL_ERROR };
}
然后,您可以通过在正确的时间调度这些操作来利用它们。
export const getWorkexperience = () => dispatch => {
dispatch(beginApiCall());
axios
.get('/api/workexperiences')
.then(res =>
dispatch({
type: GET_WORKEXPERIENCE,
payload: res.data
})
).catch (err => dispatch(apiCallError(error)););
};
然后您必须为此操作创建一个新的减速器。为此编写一个减速器有点棘手。您需要存储正在进行的 API 调用数量,并根据其状态增加或减少它们。为此,您可以附加_SUCCESS
到所有动作创建器和减速器中现有的动作类型。
import * as types from "../actions/actionTypes";
import initialState from "./initialState";
function actionTypeEndsInSuccess(type) {
return type.substring(type.length - 8) === "_SUCCESS";
}
export default function apiCallStatusReducer(
state = initialState.apiCallsInProgress,
action
) {
if (action.type == types.BEGIN_API_CALL) {
return state + 1;
} else if (
action.type === types.API_CALL_ERROR ||
actionTypeEndsInSuccess(action.type)
) {
return state - 1;
}
return state;
}
//initialState.js
export default {
state1: [],
state2: [],
apiCallsInProgress: 0
};
一旦进入组件,在发出获取请求后,您可以使用此减速器的状态来渲染旋转器或任何您想要的东西,只需从减速器中获取它即可。
const loading = useSelector((state) => state.apiCallsInProgress > 0);
或者您可以通过以下方式访问它mapStateToProps
像这样,我看到你已经用它来获取组件中的道具。
const mapStateToProps = (state) => ({
resume: state.resume,
isAuthenticated : state.auth.isAuthenticated,
auth: state.auth,
loading: state.apiCallsInProgress > 0
});
你可以像这样返回函数的内容。
{loading ? (
Loading...
) : (
<div>My component</div>
)}