【发布时间】:2017-02-11 21:08:01
【问题描述】:
我对这个简单的问题有点困惑!我想简单地获取我的表单数据,验证它,提交它并向 Express API 提交一个发布请求。但在此之前,我认为我对如何实现这一点没有透彻的了解。我查看了this 问题和these 以及其他一些问题,但我不确定这是最好的方法。
这就是我假设的方式:
我为注册页面创建了一个 React 组件。 (为演示而简化)
class SignupForm extends Component {
constructor(props){
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(val){
debugger;
}
render(){
return (
<form onSUbmit={ (e)=> this.onSubmit(e) }>
<input type="text" />
<label></label>
<button type="submit">Submit</button>
</form>
)
}
}
当按钮被点击时,OnSubmit() 函数触发,它将被传递 JSON 数据。
{
"name": "Kanye",
"surname": "West",
"email":"yeezy@goodmusic.com",
"password":"notsurehowthiswillwork"
}
我可以在哪里触发我的操作
SignupAction(),这将对我的 API 进行 AJAX 调用,然后更新我的减速器。
在使用像 react-redux-form 或 redux-form 这样的库时,困惑会成倍增加。我只想简单地为name、surname、email 和password 提供一个模型或其他东西,但我觉得这些库一旦开始拥有自己的减速器就被过度设计了:
const store = createStore(combineForms({
user: initialUser,
}));
我的另一个选择是:
class SignupForm extends Component {
constructor(props){
super(props);
this.state.form = {
name : '',
surname: '',
email: '',
password: ''
}
}
onSubmit(e){
e.preventDefault();
this.props.SignupAction(this.state.form);
// then reset the state agian to ''
}
}
但是,我的问题是……这会影响性能吗?如果会,为什么?
【问题讨论】:
-
它不会影响你的表现。在这两种情况下,组件都会重新渲染相同的次数。我相信人们使用 redux-form 是因为其他好处,例如验证、将所有内容保存在一个地方等。
标签: javascript forms reactjs