Set value in field in redux form

徘徊边缘 提交于 2019-11-30 06:24:10
Julio Betta

When using redux-form, you don't need to set the value directly into the field. You can use the method initialize to populate your form. Or initialValues as a property of the object passed to redux to map state to props. The other way is to set the values individually using the function change from redux-form. In order to make it to work, you need to wrap your component with connect from react-redux. It embeds the dispatch method in your props.

import React, { Component } from 'react';
import { reduxForm, Field, change } from 'redux-form';
import { connect } from 'react-redux';

class Form extends Component {
  componentDidMount() {
    this.props.initialize({ accountno: 'some value here' });
    // set the value individually
    this.props.dispatch(change('myFormName', 'anotherField', 'value'));
  }

  render() {
    return (
      <form onSubmit={...}>
        ...
        <Field name="accountno" component={InputText} placeholder="Number" />
        <Field name="anotherField" component={InputText} />
      </form>
    )
  }
}

Form = reduxForm({ 
  form: 'myFormName' 
})(Form);

export default connect(state => ({ 
  // alternatively, you can set initial values here...
  initialValues: {
    accountno: 'some value here'
  } 
}))(Form);

Just came up against this issue as well. The solution is to use initialValues as in juliobetta's answer, however the key is to set the value to a variable, such as state.blah.

You then need to set enableReinitialize to true so that the fields get updated when the state changes:

export default connect(state => ({ 
  initialValues: {
    accountno: state.accountno,
  },
  enableReinitialize: true,
}))(Form);

Now, every time you change state.accountno, the form field will be updated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!