【发布时间】:2016-12-29 12:56:36
【问题描述】:
在 ReactJS + Redux 中,使用 Material-UI 的 TextField、http://www.material-ui.com/#/components/text-field,我目前有一个表单,用户填写 firstName、lastName、birthMonth、birthDay、birthYear。
我有以下内容,它们都有效,但似乎非常多余,尤其是对于出生日期,例如在对每个输入进行操作并在每次更改时更新它:
在组件InputComponent.js:
updateFirstName(event) {
this.props.actions.updateFirstName(event.target.value)
}
updateLastName(event) {
this.props.actions.updateLastName(event.target.value)
}
updateBirthMonth(event) {
this.props.actions.updateBirthMonth(event.target.value)
}
updateBirthDay(event) {
this.props.actions.updateBirthDay(event.target.value)
}
updateBirthYear(event) {
this.props.actions.updateBirthYear(event.target.value)
}
<TextField
hintText="Enter First Name"
onChange={this.updateFirstName}
value={this.props.userInfo.firstName}
/>
<TextField
hintText="Enter Last Name"
onChange={this.updateLastName}
value={this.props.userInfo.lastName}
/>
<TextField
hintText="Enter Birth Month"
onChange={this.updateBirthMonth}
value={this.props.userInfo.birthMonth}
/>
<TextField
hintText="Enter Birth Day"
onChange={this.updateBirthDay}
value={this.props.userInfo.birthDay}
/>
<TextField
hintText="Enter Birth Year"
onChange={this.updateBirthYear}
value={this.props.userInfo.birthYear}
/>
那么对于我的行动:
updateFirstName(eventValue) {
return {
type: 'UPDATE_FIRST_NAME',
firstName: eventValue
}
},
updateLastName(eventValue) {
return {
type: 'UPDATE_LAST_NAME',
lastName: eventValue
}
},
updateBirthMonth(eventValue) {
return {
type: 'UPDATE_BIRTH_MONTH',
birthMonth: eventValue
}
},
updateBirthDay(eventValue) {
return {
type: 'UPDATE_BIRTH_DAY',
birthDay: eventValue
}
},
updateBirthYear(eventValue) {
return {
type: 'UPDATE_BIRTH_YEAR',
birthYear: eventValue
}
},
然后在我的减速器中,userReducer.js:
const userReducer = function(userInfo = {}, action){
switch(action.type){
case 'UPDATE_FIRST_NAME':
return {
...userInfo,
firstName: action.firstName
}
case 'UPDATE_LAST_NAME':
return {
...userInfo,
lastName: action.lastName
}
case 'UPDATE_BIRTH_MONTH':
return {
...userInfo,
birthMonth: action.birthMonth
}
case 'UPDATE_BIRTH_DAY':
return {
...userInfo,
birthDay: action.birthDay
}
case 'UPDATE_BIRTH_YEAR':
return {
...userInfo,
birthYear: action.birthyear
}
default:
return userInfo
}
}
export default userReducer
对于 ReactJS + Redux,是否有更好、更合适、更高效的做法来处理某种形式的输入?
提前谢谢你!
【问题讨论】:
-
你做对了。很多样板是一个常见的抱怨。如果您还没有仔细阅读,请阅读github.com/reactjs/redux/blob/master/docs/recipes/…。
标签: javascript html reactjs redux react-jsx