【发布时间】:2020-03-23 13:38:30
【问题描述】:
我正在使用 React+Redux+Redux Thunk + Firebase 身份验证。用 Typescript 编写代码。 我的行动是:
//Type for redux-thunk. return type for rdux-thunk action creators
type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
IStoreState, //my store state
null,
Action<userActionTypes>
>
export const signInWithEmailAndPasword =(email:string, pasword:string): AppThunk=>{
return async (dispatch)=>{
auth.signInWithEmailAndPassword(email, pasword).then(response=>{
if(response.user){
const docRef = db.collection("users").doc(response.user.uid);
docRef.get().then(function(doc) {
if (doc.exists) {
const userData = doc.data(); //user data from firebase DB
//if user exists in DB, dispatch
dispatch({
type: userActionTypes.SIGN_IN_USER,
payload: userData
})
return userData;
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
}
})
.catch(err=> dispatch(setUserError(err.message)))
}
}
我的登录组件,我将在其中分派上述操作:
import React, { useState } from 'react'
//some other imports
//...
//
import { useDispatch, useSelector } from 'react-redux';
import { signInWithEmailAndPasword } from '../../redux/actions/userActions';
interface ISignInState {
email: string;
password: string;
}
const SignIn = (props:any) => {
const [values, setValues] = useState<ISignInState>({ email: '', password: '' })
const dispatch = useDispatch();
const handleInputChange = (e: React.FormEvent<HTMLInputElement>): void => {
const { name, value } = e.currentTarget;
setValues({ ...values, [name]: value })
}
const handleFormSubmit = (e: React.FormEvent) => {
e.preventDefault()
const { email, password } = values;
dispatch(signInWithEmailAndPasword(email, password))
//// -> gives error: Property 'then' does not exist on
//// type 'ThunkAction<void, IStoreState, null, Action<userActionTypes>>'
.then(()=>{
props.history.push('/');
setValues({ email: '', password: '' })
})
}
return (<div>Sign in UI JSX stuff</div>)
所以当我尝试在dispatch(signInWithEmailAndPasword(email, password)) 之后使用.then() 时,会出现错误Property 'then' does not exist on type 'ThunkAction<void, IStoreState, null, Action<userActionTypes>>'
那么我如何从 redux 操作中返回 promise 并在其上链接 .then() 呢?我一直认为 thunk 动作默认返回 Promise。
谢谢你的帮助
编辑:
临时解决方案是使用any 作为上述操作的返回类型:
export const signInWithEmailAndPasword = (email:string, pasword:string):any =>{
return async (dispatch: any)=>{
try {
const response = await auth.signInWithEmailAndPassword(email, pasword)
if(response.user){
const userInDb = await getUserFromDB(response.user)
dispatch(userSignIn(userInDb))
return userInDb
}
} catch (error) {
dispatch(setUserError(error.message))
}
}
}
但我不想使用any
【问题讨论】:
-
你可以等待 thunk - 看起来它可能只是图书馆的打字错误?如果您只是在该函数中执行
async/await会怎样 -
但是,理想情况下,thunk 操作会根据您传入的
then调度另一个操作,而不是在您的组件中执行它。 -
顺便说一句,thunk 真的很恶心,你正在使用承诺,但是嵌套它们而不是返回它们,你没有返回你的顶级承诺(这也是一个问题,即使打字稿错误不存在).....yikes all over.
-
我只需要它在成功响应后重定向。
标签: javascript reactjs redux firebase-authentication redux-thunk