简体   繁体   English

从redux-form覆盖初始值

[英]Overwrite initial value from redux-form

I am initializing values in Field using initialValues. 我正在使用initialValues在Field中初始化值。 Although I would like to overwrite one of the Field with another defaul value. 虽然我想用另一个默认值覆盖Field之一。 Is this possible? 这可能吗? I was trying with defaultValue etc but I doesnt work. 我正在尝试使用defaultValue等,但是我没有用。 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 它使用url初始化,但我想将其更改为url:port

Before passing initialValues prop down to your redux-form component, you can modify it. 在将initialValues prop传递到redux-form组件之前,您可以对其进行修改。

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. 不确定如何以及如何生成或更新urlport变量。 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 在您的Field组件中

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

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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