我正在尝试使用 react 和 redux 实现乐观的 UI 加载。这是我的减速机:
const initState = {
user: {},
loading: true,
};
export default function (state = initState, action) {
switch (action.type) {
case GET_CURRENT_USER_BY_PROFILEID_LOADING:
return {
...state,
loading: true,
};
case GET_CURRENT_USER_BY_PROFILEID:
return {
...state,
loading: false,
user: action.payload.item,
};
default:
return state;
}
}
这是动作创建者:
export const getCurrentUserByProfileId = (profileId) => {
return (dispatch) => {
dispatch({ type: GET_CURRENT_USER_BY_PROFILEID_LOADING });
baseUrl
.get(
Constants.RELATIVEPATH +
Constants.USERS +
'/' +
profileId +
Constants.PROFILEID,
{ headers }
)
.then((response) => {
const data = response.data;
dispatch({
type: GET_CURRENT_USER_BY_PROFILEID,
payload: { item: data },
});
})
.catch((error) => {
console.log(error);
onError(error);
});
};
};
理想的情况是:Loading --> New state
我只在第一次加载时得到这个,之后是:Flash of old state --> Loading --> New state