简体   繁体   中英

Getting a field value from Redux form returns 'undefined'

What I'm having makes me bang my head in the code, comparing it with the guidelines from mapStateToProps and Redux form . I'm trying to get a field value, but I'm continually receiving undefined . What I have is:

const myForm = reduxForm({
  form: 'myForm',
})(MyComponentClass);

const mapStateToProps = ((state) => ({
  l10n: l10nService,
  formValues: getFormValues('myForm')(state),
}));

export default connect(mapStateToProps)(myForm);

When I try to output formValues like

console.log(formValues);

I'm getting constantly undefined. This is frustrating as I'm re-reading the docs and can't find where the problem is. I'm visualizing the field with a method like this:

addSelectFieldD(element, key) {
  return (<Field
    key={key}
    name={element.name}
    label={l10nService.translate(element.label)}
    component={SelectField}
    units={element.units}
    options={this.props.selectOptions}
    onChangeDuration={this.onChangeDuration}
    onRetrieveSelectOptionsError={this.onRetrieveSelectOptionsError}
    informationMessage={l10nService.translate(element.tooltip)}
    submitted={this.state.formSubmitted}
  />);
}

Interesting thing is that I'm able to get formValues in some other component. I would highly appreciate any help guys as I'm so stacked with this.

EDIT: I've created an example here

okay so i have figured out the problem, in redux form if you dont provide some initial value to a form field it will be undefined rather than an empty object.

To give you an idea i have updated the sandbox with the initial value for the field so now on this.props.formValues you will get the default value of the field, obviously onChange is not handle so it remains the same even if you change the value from dropdown, you can change that, but you get the idea,

Here you can look how its done, basically i have provided the initial value for form as

const myForm = reduxForm({
form: "myForm",
initialValues: {
 my: "value1",
 },
})(MyForm);

UPDATE: As you are using react-select as the select component so you need to dispatch a change action when you change dropdown value as

onChangeSelect = (props, newOption) => {
  this.props.dispatchChange(formName, fieldName, value)
} 

I have updated sandbox for complete working example of your case Hope it helps now

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