简体   繁体   中英

Overwrite initial value from redux-form

I am initializing values in Field using initialValues. Although I would like to overwrite one of the Field with another defaul value. Is this possible? I was trying with defaultValue etc but I doesnt work. This is the part of code I want to change:

<Field
  type="text"
  name={`${some}.url`}
  component={renderField}
  label="URL"
  defaultValue={some.url + ':' + some.port}
/>

Its initialized with url, but I would like to change it to url:port

Before passing initialValues prop down to your redux-form component, you can modify it.

Something like that:

const mapStateToProps = state => ({
  // Here's how to set a default value and overwrite the API initial data.
  // Let's say your form is editing an User.
  // And if the User, returned by the API, doesn't have a name,
  // then we set a default value.
  initialValues: {...state.user, name: state.user.name || 'Default name'}
)}

// `connect` is part of `react-redux`.
// If you don't use `react-redux`, then just modify the `initialValues`
// before passing it down to the form.
export default connect(mapStateToProps)(reduxForm({
  form: 'formName',
})(Component))

Not sure what and how you generate or update your url and port variables. But something like this should work. If you can share more details, I can adapt the answer.

private url: string = `${some}.url`;
private port: string = `${some}.port`;

<Field
  type="text"
  name={this.url}
  component={renderField}
  label="URL"
  defaultValue={this.url + ':' + this.port}
  updateDefaultValue={(url, port) => {this.url = url; this.port = port}}
/>

in your Field component

this.props.updateDefaultValue("xxx","yyy");

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM