我是React的新手,正在建立一个与后端JSON api绑定的注册/登录功能。 我有一个注册表单组件,在按下提交按钮时进行API调用。 API调用由身份验证服务处理。 我希望在API发生故障响应的情况下更新初始组件的状态,并且似乎无法弄清楚如何做到这一点,因为一旦在catch块中我无法访问组件的状态。以下是组件的代码:
import React from 'react';
import Auth from '../services/AuthService';
import {ButtonInput, Panel} from 'react-bootstrap';
import {Form, ValidatedInput} from 'react-bootstrap-validation';
import {Radio, RadioGroup} from 'react-bootstrap-validation';
import Loader from 'react-loader-advanced';
export default class Signup extends React.Component {
constructor() {
super();
this.state = {
loader: false
};
}
_handleValidSubmit(values) {
this.setState({loader: true});
Auth.signup(values.email, values.password, values.firstName, values.lastName)
.catch(function (err) {
var response= JSON.parse(err.response);
var errors = response.error;
var errorText = '';
for (var k in errors){
if (errors.hasOwnProperty(k)) {
errorText = errorText + errors[k] + '\n';
}
}
alert(errorText);
return false;
});
}
_handleInvalidSubmit(errors, values) {
}
render() {
return (
<Panel>
<Form onValidSubmit={this._handleValidSubmit.bind(this)}
onInvalidSubmit={this._handleInvalidSubmit.bind(this)}>
<ValidatedInput
type='email'
name='email'
label='Email'
errorHelp={{
required: 'Please enter your email',
isEmail: 'Please enter a valid email'
}}/>
<ValidatedInput
type='password'
name='password'
label='Password'
validate='required,isLength:6:60'
errorHelp={{
required: 'Please specify a password',
isLength: 'Password must be at least 6 characters'
}}/>
<ValidatedInput
type='text'
name='firstName'
label='First Name'
validate='required,isAlpha,isLength:2:200'
errorHelp={{
required: 'Please enter your first name',
isAlpha: 'Please enter a valid first name',
isLength: 'Please enter a valid first name'
}}/>
<ValidatedInput
type='text'
name='lastName'
label='Last Name'
validate='required,isAlpha,isLength:2:200'
errorHelp={{
required: 'Please enter your last name',
isAlpha: 'Please enter a valid last name',
isLength: 'Please enter a valid last name'
}}/>
<Loader show={this.state.loader} message={'loading'}>
<ButtonInput
type='submit'
bsSize='large'
bsStyle='primary'
value='Register'
/>
</Loader>
</Form>
</Panel>
)
}
}
我想要做的是在_handleInvalidSubmit的catch块中添加this.setState({loader: false});
之类的内容以取消加载并重新呈现组件 - 但是一旦在catch块内,回调就无法访问组件上下文。
在此先感谢您的帮助!
答案 0 :(得分:0)
您可以使用Javascript闭包来帮助自己,并执行以下操作:
_handleValidSubmit(values) {
this.setState({loader: true});
var that = this;
Auth.signup(values.email, values.password, values.firstName, values.lastName)
.catch(function (err) {
that.setState({loader: false});
var response= JSON.parse(err.response);
var errors = response.error;
var errorText = '';
for (var k in errors){
if (errors.hasOwnProperty(k)) {
errorText = errorText + errors[k] + '\n';
}
}
alert(errorText);
return false;
});
}
这是JS中非常标准的技巧。
答案 1 :(得分:0)
如果您使用的是转换器,则可以在catch处理程序中使用匿名函数。
...catch(err=>{this.setState( {loader: false})});