延迟React Redux Action从输入调度

时间:2017-09-15 05:16:32

标签: javascript reactjs redux

如下面的代码所示,我在onChange事件中调用调度动作函数。所以每当我按任意键时,它都会调度redux动作。我认为这不是一个好方法。因为如果我写了“aaaa'”,那么行动就会发送4次&通过reducer更新状态。

我不想使用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;
}

1 个答案:

答案 0 :(得分:1)

利用debounce并在一定的去抖时间间隔后调用动作调度,因此如果用户不断发送行动,则不会发出动作,但会在稍微暂停时执行此操作。

constructor(props) {
    super(props);
    this.onFieldChange = _.debounce(
       this.onFieldChange,
            150
    );
  }

  onFieldChange = (fieldName, e) => {
    e.persist();
    this.props.updateFields(`fields.${fieldName}`, e.target.value);
  }