1
如下面的代碼所示,我打電話onChange事件調度動作功能。所以每次當我按下任意鍵,它將派遣了Redux行動。我認爲這不是一個好方法。因爲如果我寫「AAAA」,那麼行動將派遣4倍&通過減速機更新狀態。陣營終極版動作調度
我並不想用的onblur事件,因爲有時這是行不通的。什麼是優化代碼的最佳方法?
部件
class abc extends Component {
constructor(props) {
super(props);
}
onFieldChange(fieldName, e) {
e.persist();
this.props.updateFields(`fields.${fieldName}`, e.target.value);
}
render() {
const {fields} = this.props.facilityFormStates;
return (
<div>
<div className='col-md-12'>
<TextField
defaultValue={fields && fields.fullLegalName}
onChange={(e) => this.onFieldChange('fullLegalName', e)}
floatingLabelText="Full Legal Name *"
floatingLabelFixed={true}
fullWidth={true}
/>
<TextField
hintText=""
defaultValue={fields && fields.businessName}
onChange={(e) => this.onFieldChange('businessName', e)}
floatingLabelText="Business or Assumed Name, if any"
floatingLabelFixed={true}
fullWidth={true}
/>
<TextField
hintText=""
defaultValue={fields && fields.employerNumber}
onChange={(e) => this.onFieldChange('employerNumber', e)}
floatingLabelText="Federal Employer Identification Number"
floatingLabelFixed={true}
fullWidth={true}
/>
<TextField
hintText=""
defaultValue={fields && fields.address}
onChange={(e) => this.onFieldChange('address', e)}
floatingLabelText="Street Address"
floatingLabelFixed={true}
fullWidth={true}
/>
</div>
<br />
</div>
);
}
}
const mapStateToProps = (state) => ({
facilityFormStates: state.facilityFormStates,
})
const mapDispatchToProps = (dispatch) => ({
updateFields: (path, data) => dispatch(updateFieldsFormField(path, data))
})
export default connect(mapStateToProps, mapDispatchToProps)(abc);
行動
import {UPDATE_FORM_ACTION} from './action-types.js'
export const updateFormField = (ObjKeyPath, value) => {
return {
type: UPDATE__FORM_ACTION,
ObjKeyPath,
value,
}
}
減速器
import {UPDATE_FORM_ACTION} from '../../actions/action-types.js';
import _ from 'lodash';
export default function (state = {}, action) {
switch (action.type) {
case UPDATE_FORM_ACTION:
return _.set(state, action.ObjKeyPath, action.value)
}
return state;
}
化妝用反跳和呼叫一定去抖動間隔之後的動作調度,所以如果使用不斷將綁你不派遣行動,但這樣做時,有一個短暫的停頓 –
@ShubhamKhatri你能請在這裏寫出去抖語法?我正在使用lodash庫。 – Shubham