Javascript redux操作将未定义的返回到视图
我创建了一个简单的登录表单,效果很好。我想在API调用失败(登录失败)时返回错误消息 视图的Login.js文件Javascript redux操作将未定义的返回到视图,javascript,reactjs,redux,Javascript,Reactjs,Redux,我创建了一个简单的登录表单,效果很好。我想在API调用失败(登录失败)时返回错误消息 视图的Login.js文件 async handleSubmit(event) { let userLoginObject = { login: this.state.username, password: this.state.password, } if (!isEmptyOrNull(this.state.username) &&
async handleSubmit(event) {
let userLoginObject = {
login: this.state.username,
password: this.state.password,
}
if (!isEmptyOrNull(this.state.username) &&
!isEmptyOrNull(this.state.password)) {
let resp = await this.props.onUserLogin(userLoginObject)
console.log("resp",resp) // this shows 'undefined'
this.setState({ formError: resp }); //Im trying to set state to the formError
}
}
动作文件
export const onUserLogin = (userLoginData) => async (dispatch) => {
const loginResponse = await doUserLogin(userLoginData)
dispatch({
type: ACTION_LOGIN,
data: loginResponse,
})
if (loginResponse.token) {
history.push('/investments')
}
else {
console.log("error",loginResponse.error) // this shows the error message
return loginResponse
}
}
登录尝试失败后,我的控制台如下
resp undefined
token:1 POST http://localhost:8000/token 400 (Bad Request)
authActions.js:52 error invalid credentials
它显示未定义
,即使我在操作中只返回了一个字符串
这里怎么了?当API调用失败时,我如何返回错误消息。我认为您的问题在于您使用的是
async/await
,但仅当doUserLogin
成功时才处理该情况。请记住,async/await
基本上只是糖衣炮弹
试试这个:
const loginResponse;
try {
loginResponse = await doUserLogin(userLoginData)
dispatch({
type: ACTION_LOGIN,
data: loginResponse,
})
if (loginResponse.token) {
history.push('/investments')
}
} catch (e) {
console.log("error", e) // this shows the error message
return e
}
使用回调函数而不是返回错误(可能无法从redux操作返回任何内容) 使用回调函数
this.props.onUserLogin(userLoginObject, error => {
// Called when error is occurred
this.setState({ formError: error });
});
由于您已经在使用redux,我建议您使用一种不同的方法,即如果在分派操作中您实际将错误消息保存为道具(如果是这样),然后在组件中显示它。而不是使用 this.setState({formError:resp}) 您可以直接从redux恢复错误
此.props.errorLogin感谢您的回复。它不起作用。输出的控制台与上面的控制台相同,上面写着
onError(loginResponse.error)
不是一个函数您需要在调用函数时将函数作为参数传递。这里,onUserLogin操作有两个参数,一个用于数据,另一个是发生错误时调用的回调函数。您还需要在调用此操作时传递函数。像这样=>this.props.onUserLogin(userLoginObject,error=>{//发生错误时调用this.setState({formError:resp});})
this.props.onUserLogin(userLoginObject, error => {
// Called when error is occurred
this.setState({ formError: error });
});