Redux dispatch不是Next.js+;thunk在用户登录后加载数据
当我尝试getUserProfile()时,我收到一个类型错误,即dispatch不是一个函数 未处理的运行时错误 错误:操作必须是普通对象。使用自定义中间件进行异步操作Redux dispatch不是Next.js+;thunk在用户登录后加载数据,redux,next.js,dispatch,thunk,Redux,Next.js,Dispatch,Thunk,当我尝试getUserProfile()时,我收到一个类型错误,即dispatch不是一个函数 未处理的运行时错误 错误:操作必须是普通对象。使用自定义中间件进行异步操作 export const fetchUserProfile = (userData) => ({ type: types.GET_USER_PROFILE, userData, }); //砰 export const loginUser = (credentials) => async (dispatch)
export const fetchUserProfile = (userData) => ({
type: types.GET_USER_PROFILE,
userData,
});
//砰
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();
与
您的
getUserProfile
应该是一个在分派时接受自己的参数的函数,然后它可以是一个回调函数,接受dispatch
作为参数(这来自Redux Thunk中间件),然后该函数具有返回action
对象的函数,或者它可以只是一个直接返回操作
对象的函数(我知道这很混乱,但实际上您为登录用户
操作正确地执行了该操作):
export const getUserProfile=()=>async(dispatch)=>{
试一试{
const profileData=await userService.getProfileData();
调度(fetchUserProfile(profileData));
}捕获(e){
控制台日志(e);
return[];//这不应该返回一个空数组,如果有的话,它应该为可以显示给用户的错误分派一个操作
}
};
这个过于简单的示例可以让您了解正在发生的事情(单击运行代码片段
):
//将从
//Redux Thunk中间件
const dispatch=(action)=>action((args)=>console.log(“dispatch:,JSON.stringify(args,null,2));
//返回对象的“setUserProfile”操作
const setUserProfile=(有效负载)=>({
类型:“设置配置文件”,
有效载荷
});
//返回对象的“fetchUserProfile”操作
const fetchUserProfile=()=>({type:“FETCH_USER”});
//返回一个对象的“淋浴错误”操作
const-showError=error=>({type:“FETCH_USER/error”,有效负载:error});
//而“getUserProfile”操作没有任何
//它本身接受一个“dispatch”回调函数作为第二个函数
//一组参数,然后调度其他操作(返回
//(他们自己的目标)
const getUserProfile=()=>async(dispatch)=>{
试一试{
//分派“fetchUserProfile”操作
//它只返回:{type:“FETCH_USER”}
分派(fetchUserProfile());
//从API获取数据
const res=等待获取(“https://jsonplaceholder.typicode.com/users/1");
const data=wait res.json();
//使用来自API的数据分派“setUserProfile”
//返回:{type:“SET_PROFILE”,有效负载:data}
调度(setUserProfile(数据));
}捕获(e){
控制台日志(e);
派遣(电子邮件);
}
};
//调度上面的“getUserProfile”函数
//或者,您可以在这里添加参数,但这些参数将是
//函数的第一组参数的一部分
调度(getUserProfile())代码>
之后我收到:错误:操作必须是普通对象。使用自定义中间件进行异步操作。
dispatch(getUserProfile())