我对 React 很陌生,遇到了 useReducer。如果我在这里粘贴我的代码会很长,因为它涉及到组件,useContext和useReducer。所以我将只粘贴一些代码。我对 try and catch 循环中的状态有疑问。我的 reducer 启动了一个使用 firebase signInWithEmailAndPassword() 的登录方法。我做错了 try and catch 循环吗?我可以在 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 更新状态时遇到了问题。