我正在使用Axios从React客户端登录api服务。名称和密码的表单由final-form处理。除了我想从onSubmit函数返回错误之外,一切都像预期的那样工作。
有两个组件:父Login,它使用logIn函数处理对API的调用;嵌套组件LoginUi,它具有表单和onSubmit函数,它通过this.props.logIn()调用父方法logIn。
下面是父Login组件中的logIn方法:
class Login extends Component {
constructor() {
super();
this.logIn = this.logIn.bind(this);
}
logIn(credentials) {
return axios({
method: 'post',
url: 'http://0.0.0.0:3000/v1/login/',
data: {
name: credentials.name,
password: credentials.password,
},
})
.then((response) => {
return response;
})
.catch((error) => {
return error;
});
}
render() {
return <LoginUi logIn={this.logIn} {...this.props} />;
}
}
export default Login;下面是子LoginUi组件中的onSubmit方法:
class LoginUi extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(credentials) {
this.props
.logIn(credentials)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
return { [FORM_ERROR]: 'Login Failed' };
});
}
render() {
return (
<div className="LoginUi">
{/* here goes the form with final-form, not included for brevity */}
</div>
);
}
}
export default LoginUi;{ [FORM_ERROR]: 'Login Failed' }负责通过final-form-更改表单-handled的状态,但它无法执行此操作。如果我在catch外部返回它,它可以工作:
onSubmit(credentials) {
this.props
.logIn(credentials)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
return { [FORM_ERROR]: 'Login Failed' };
}但这显然不是我想要的,因为[FORM_ERROR]: 'Login Failed'必须在API调用返回错误时才返回。
我很确定在这里使用promises是一个问题。如果任何人有任何想法,我将不胜感激!
谢谢!
发布于 2019-03-16 17:40:01
由于您依赖于promise,因此onSubmit应该返回promise。将return添加到onSubmit,否则它将返回undefined,并且final-form无法知道axios调用是否已完成:
onSubmit(credentials) {
return this.props
.logIn(credentials)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
return { [FORM_ERROR]: 'Login Failed' };
});
}https://stackoverflow.com/questions/55195286
复制相似问题