尝试使用反应钩子重写此方法:
this.setState({
isPerformingAuthAction: true
}, () => {
auth.signInWithEmailAndPassword(emailAddress, password).then((value) => {
this.closeSignInDialog(() => {
const user = value.user;
const displayName = user.displayName;
const emailAddress = user.email;
this.openSnackbar(`Signed in as ${displayName || emailAddress}`);
});
}).catch((reason) => {
const code = reason.code;
const message = reason.message;
switch (code) {
case 'auth/invalid-email':
case 'auth/user-disabled':
case 'auth/user-not-found':
case 'auth/wrong-password':
this.openSnackbar(message);
return;
default:
this.openSnackbar(message);
return;
}
}).finally(() => {
this.setState({
isPerformingAuthAction: false
});
});
});
isPerformingAuthAction 是一个组件属性,用于在执行各种操作时禁用按钮。
<Button disabled={state.isPerformingAuthAction} ... />
问题:我正在使用 useReducer 来管理本地状态,而 isPerformingAuthAction 是 reducerState 的一个属性。useReducer 不返回承诺,所以我不能这样做:
dispatch({type:"isPerformingAuthAction", payload: true}).then(auth.stuff)
我考虑过改用 useState ,但它没有像 this.setState 这样的回调。
我一直在尝试围绕一些 useEffect 方法来获取数据和异步。我对此感到很困惑,但我认为我可以将“isPerformingAuthAction”或reducer的状态作为依赖项,并在组件更改时使用useEffect更新组件,但“isPerformingAuthAction”属性也因其他原因而更改,而不仅仅是auth.signInWithEmailAndPassword(emailAddress, password)
,但 signUp、signOut 和其他一些。
因此,当“isPerformingAuthAction”更改为 true 时,它会禁用按钮,因此用户被迫等待来自服务器的响应。在调用 auth.whatever 之前,我想确保这些按钮被禁用(状态更新/组件用灰色按钮重新渲染)。