[英]Redux thunk async action cannot access first parameter
我有一个当前使用.then
可以正常工作的操作.then
但是当我尝试将其转换为async ... await
它突然无法访问该函数的第一个参数。 不过,第二个参数仍然可以正常工作。
当前工作正常的功能:
export const signInUser = (email, password) => {
return (dispatch) => {
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(() => {
console.log('signed in')
const { uid, email } = firebase.auth().currentUser
dispatch({ type: 'SIGN_IN', uid, email })
return dispatch(fetchAllData())
})
.catch(error => {
throw (error)
})
}
};
由于未定义“电子邮件”而不起作用的新函数。
export const signInUser = (email, password) => {
return async (dispatch) => {
console.log('testing')
console.log(password)
console.log('testing', email, password)
await firebase.auth().signInWithEmailAndPassword(email, password)
console.log('signed in')
const { uid, email } = firebase.auth().currentUser
dispatch({ type: 'SIGN_IN', uid, email })
return dispatch(fetchAllData())
}
};
console.log('testing')
的第一个控制台日志工作正常并输出字符串 'testing'。 console.log(password)
的第二个控制台日志也可以正常工作并打印输入的密码。 但是第三个控制台日志console.log('testing', email, password)
根本没有显示。
函数是这样调用的:
父组件将其传递给子组件: submit={(email, password) => dispatch(signInUser(email, password))}
子组件调用它:
const submitForm = (event) => {
event.preventDefault();
if (validForm) {
setLoading(true)
submit(email, password)
.catch(err => {
setLoading(false)
console.log('catch:', err.code)
setError(err.code)
})
}
}
我收到的输出是catch: undefined
。
另外,如果我将功能更改为:
export const signInUser = (email, password) => {
const userEmail = email
return async (dispatch) => {
console.log('testing')
console.log(password)
console.log('testing', userEmail, password)
await firebase.auth().signInWithEmailAndPassword(userEmail, password)
console.log('signed in')
const { uid, email } = firebase.auth().currentUser
dispatch({ type: 'SIGN_IN', uid, email })
return dispatch(fetchAllData())
}
};
然后它工作正常。 但我不知道为什么我需要像这样改变它?
谢谢
好的,它不起作用的原因是因为在下一行我声明了这样的电子邮件const { uid, email } = firebase.auth().currentUser
它覆盖了email
的函数参数,因此给了我这样的错误我在声明之前使用email
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.