我是 React/Redux 的初学者。 我想对用户进行身份验证并在发生错误时在我的应用程序上显示通知。
这是我的登录功能:
const [loading, setLoading] = useState(false);
const dispatch = useDispatch();
const handleSignIn = (values: SignInOpts, setSubmitting: any) => {
setLoading(true);
dispatch(authenticationActions.signInAndFetchUser(values))
.then(res => {
console.log("SignIn Success");
setLoading(false);
})
.catch(err => {
console.log("SignIn Failure");
setLoading(false);
showErrorNotification(
"Error notification"
);
});
};
我的行动:
export const signInAndFetchUser = (credentials: SignInOpts) => {
return (dispatch, getState) => {
return dispatch(signIn(credentials)).then(res => {
const token = getState().authentication.token;
return dispatch(getMe(token));
});
};
};
我遇到的错误:
我该如何执行此操作?
最佳答案
一般来说,对于 thunk,dispatch(myThunk())
将返回无论 thunk 返回什么,并且可以是一个 Promise,情况也是如此在您的 signInAndFetchUser
方法中。
问题是正常的 useDispatch
钩子(Hook)类型不知道您正在使用哪个中间件,因此没有该行为的重载。
这就是 Redux TypeScript Quickstart Tutorial 的原因建议您定义自己的、类型正确的 Hook :
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
如果你使用官方的 Redux Toolkit(尤其是 TypeScript,你绝对应该这样做,因为它删除了几乎所有类型注释),你可以得到
export type AppDispatch = typeof store.dispatch
如果您使用旧式 vanilla Redux,只需使用 ThunkDispatch
作为 AppDispatch
。
关于reactjs - React/Redux/Typescript - useDispatch 和 .then().catch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68035932/