如何使用redux-form中的formValueSelector在更改时获取更新的输入字段值

时间:2017-10-27 13:32:50

标签: javascript redux-form

我正在使用redux-formformValueSelector从字段中获取输入值。我希望获得改变的价值,但在我的函数调用@@redux-form/CHANGE后调用onChange动作。所以我没有更新价值。我的代码:

export class PersonFilter extends React.Component {
  constructor(props) {
    super(props);
  }

  filterByName = (event, searchName) => {
    //here searchName is getting old value
    store.dispatch({type: 'PERSON_FILTER_BY_NAME', payload: {name: searchName}});
  };


  render() {
    const {
      searchName
    } = this.props;

    return (
      <form className="person person--filter" onSubmit={e => {
        e.preventDefault();
        this.filterByName(e, searchName)
      }}>
        <Field
          onChange={e => {
            this.filterByName(e, searchName)
          }}
          className="person__input" icon="search"
          name="searchName" component={renderField} type="text"
          placeholder="Name"/>

      </form>
    );
  }
}



PersonFilter = reduxForm({
  form: 'filter',
  initialValues: {
    searchName: store.getState().personsFilterReducer.filterByName
  }

})(PersonFilter);

const selector = formValueSelector('filter');

PersonFilter = connect(state => {
  const searchName = selector(state, 'searchName');
  return {
    searchName
  }
})(PersonFilter);

和包装器组件:

class Persons extends React.Component {
  constructor() {
    super();
  }

  render() {
    return (
      <div>
        <PersonFilter/>
      </div>  
    };    
  }
}  

1 个答案:

答案 0 :(得分:1)

不要只是将onChange传递给你应该setState的动作,首先在包装器组件构造函数中初始化状态this.state,并确保将 props 传递给构造函数好吧,然后在onChange函数this.setState中设置一个状态并绑定它。 像这样:

包装组件

class Persons extends React.Component {
    constructor (props) {
        super(props);
        this.state = {} 
    }
    onChange(field, value) {   
        this.setState({[field]: value});
    }
    render () {
        return <PersonFilter onChange={this.onChange.bind(this)} />
    }
}

PersonFilter组件内部创建一个函数onFieldChange,它将对包装器组件中的函数onChange的引用传递给设置状态this.setState

export class PersonFilter extends React.Component {
  constructor(props) {
    super(props);
  }

    onFieldChange(event) {
        const changeName = event.target.name;
        const changeValue = event.target.value;
        this.props.onChange(fieldName, fieldValue);
    }

然后最后

     <Field
      onChange={this.onFieldChange.bind(this)}
      className="person__input" icon="search"
      name="searchName" component={renderField} type="text"
      placeholder="Name"/>