问题描述
当我尝试 getUserProfile()时,我收到调度不是函数的typeError
未处理的运行时错误 错误:动作必须是普通对象。使用自定义中间件执行异步操作。
export const fetchUserProfile = (userData) => ({
type: types.GET_USER_PROFILE,userData,});
// thunk
export const loginUser = (credentials) => async (dispatch) => {
dispatch(loginRequest(credentials));
try {
const userToken = await userService.login(credentials);
await dispatch(loginSuccess(userToken));
getUserProfile();
} catch (error) {
const message = await errorMessage(
error,"There was a problem processing your request"
);
dispatch(loginFailure(message));
}
};
export const getUserProfile = async (dispatch) => {
try {
const profileData = await userService.getProfileData();
dispatch(fetchUserProfile(profileData));
} catch (e) {
console.log(e);
return [];
}
};
解决方法
您需要分派所有重击,替换
getUserProfile();
使用
dispatch(getUserProfile())
,
您的getUserProfile
应该是一个在您分派时接受其自身参数的函数,然后它可以是一个接受dispatch
作为参数的回调函数(这来自Redux Thunk中间件),然后该函数具有返回action
对象的函数,或者它可以只是直接返回action
对象的函数(我知道这很困惑,但实际上您为{{1 }}操作):
loginUser
这种过于简单的示例类型使您可以了解正在发生的事情(单击export const getUserProfile = () => async (dispatch) => {
try {
const profileData = await userService.getProfileData();
dispatch(fetchUserProfile(profileData));
} catch (e) {
console.log(e);
return []; // this shouldn’t be returning an empty array,if anything it should be dispatching an action for errors that can be displayed to the user
}
};
):
Run code snippet
// the "dispatch" function that would come from
// the Redux Thunk middleware
const dispatch = (action) => action((args) => console.log("dispatch:",JSON.stringify(args,null,2)));
// a "setUserProfile" action that returns an object
const setUserProfile = (payload) => ({
type: "SET_PROFILE",payload
});
// a "fetchUserProfile" action that returns an object
const fetchUserProfile = () => ({ type: "FETCH_USER" });
// a "showError" action that returns an object
const showError = error => ({ type: "FETCH_USER/ERROR",payload: error });
// while the "getUserProfile" action doesn't have any arguments of
// its own,it accepts a "dispatch" callback function as the SECOND
// set of arguments,then other actions are dispatched (which return
// their own objects)
const getUserProfile = () => async(dispatch) => {
try {
// dispatches the "fetchUserProfile" action
// which just returns: { type: "FETCH_USER" }
dispatch(fetchUserProfile());
// fetching data from API
const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
const data = await res.json();
// dispatches the "setUserProfile" with data from API
// which returns: { type: "SET_PROFILE",payload: data }
dispatch(setUserProfile(data));
} catch (e) {
console.log(e);
dispatch(showError(e.message));
}
};
// dispatching the "getUserProfile" function above
// optionally,you can add arguments here,but then these would be
// a part of the FIRST set of arguments to the function
dispatch(getUserProfile());