问题描述
我对React很陌生,遇到过useReducer。 如果我在这里粘贴代码,那会很长,因为它涉及组件,useContext和useReducer,因此我只会粘贴一些代码。 我对try and catch循环中的状态有疑问。 我的reducer启动了一个使用firebase signInWithEmailAndPassword()的登录方法。我是否在尝试捕获循环错误?我可以在console.log中看到错误消息,但是无论是在then()。catch()还是在try and catch循环中,错误消息都不会更新我的状态。
const loginUser = (usename,password,state) => {
try{
const res = auth.signInWithEmailAndPassword(email,password).then( user => {
return {...state,userid: user.uid}
}).catch(error => {
return {...state,error: error.message}
})
}catch (error) {
console.log("oops !! error: ",error);
return {...state,error: error,isLoggedIn:false,isLoading:false};
}
}
export const storeReducer = (state,action) => {
switch (action.type) {
case USER_LOGIN:
return loginUser(action.username,action.password,state);
default:
return state;
}
};
上面的代码是一个简化的版本,我在使用useReducer更新状态时遇到了问题。
解决方法
我会将您的loginUser
函数更改为这样的内容...
const loginUser = async (usename,password,state) => {
try{
const response = await auth.signInWithEmailAndPassword(email,password)
return // return user here
}catch (error) {
console.log("oops !! error: ",error);
return // return error here
}
}
并且您应该基于此函数的返回调度 action 或从此函数调度。您应该不要将此函数放置在减速器中,因为它是异步的,而减速器应该是纯函数
应该更像是...
loginUser.then(data => {
// dispatch accordingly
})