我是一个反应新手(我的道歉)。我有点卡在这一个。防止无状态下的双重提交反应形式
我使用提交按钮来构建一些反应组件,这些组件可以调用RESTful API。随着状态组件,这里是我是如何防止“双重的提交”(本质上的变化的状态,而请求处理)
class Submitter extends React.Component {
constructor(props) {
super(props);
this.state = { buttonDisabled: false, buttonText: 'Save' };
this.saveQuestion = this.saveQuestion.bind(this);
}
saveToApi() {
const _this = this;
this.setState({ buttonDisabled: true, buttonText: 'Saving' });
request((err, res) => {
_this.setState({ buttonDisabled: false, buttonText: 'Save' });
});
}
render() {
return (<div>
<TextInput />
<Button
disabled={this.state.buttonDisabled}
onClick={this.saveToApi}>
{this.state.buttonText}
</Button>
</div>);
}
}
这工作很大。我开始使用react-form来做一些更高级的验证等等。但是,这是一个无状态的组件,我对如何做到这一点不知所措。我没有使用redux,但是如果需要,我可以使用。即使我使用了redux,我也不确定关于如何去做的一般策略。这是我的工作登录表单,但它不妨碍双重提交。
const LoginForm = Form({
validate: values => {
const { email, password } = values;
return {
email: (!email || !/^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)) ? 'A valid email is required' : undefined,
password: (!password || password.length < 6) ? 'Passwords must be longer than 6 characters' : undefined,
};
},
})(({ submitForm }) => (<form onSubmit={submitForm}>
<FormTextInput htmlId="email" label="Email Address" />
<FormTextInput htmlId="password" label="Password" type="password" />
<Button colored type="raised" htmlType="submit" >Login</Button>
</form>
));
export default() => (
<LoginForm
onSubmit={(values) => {
request((err, res) => {
if (res.body.login) {
history.push('/app');
} else {
msg.error(res.body.message);
}
});
}}
/>
);
这将适用于第一个例子,但我对第二个例子更感兴趣。 – renegadeborealis