简体   繁体   中英

Set redux-form Field value based on TWO other fields

So, in redux-form, I have seen many ways of updating a Field 's value based on another Field . My particular situation is updating a Field 's value based on two different Fields .

The two popular ways suggested to achieve this are 1.) redux-form's normalizer , and 2.) manually dispatching redux-form's change method to change Field3 's value, when the onChange for Field1 is called. Both these solutions do not seem to be working for me for the following reasons:

  1. Normalizer : Let's say I have 3 fields - Field1 , Field2 and Field3 . I need to set the value of Field3 when either of Field1 or Field2 are changed. Also the value of Field2 is automatically set when Field1 is changed . Let's say I define a normalizer on Field1 , which checks the values of the entire form. In this case, inside my normalizer function, Field1 's value gets updated, but Field2 retains it's old value. This could be some odd behavior from redux-form maybe.

  2. Manually dispatching redux-form's change method on Field3 , from inside Field1 's or Field2 's onChange - The problem with this is that if I try to access Field1 's value inside Field1 's onChange , the method passed to Field1 's onChange retains Field1 's old value. Hence I can't reliably set the value of Field3 based on Field1 's new value.

Any suggestions as to how to approach this would be helpful. Thanks!

try this:

create a component for field3 (say Field3) and use it in the form like this

<Field name="field3" component={Field3} />

in Field3 component we also inject the field1 and field2 value to Field3 component. so that whenever the component updated we can check if it's because of field1 or field2 then we update field3 accordingly:

import React from 'react';
import { formValues } from 'redux-form';

class Field3 extends React.Component {
  componentDidUpdate(prevProps) {
    if (this.props.field1 !== prevProps.field1 || this.props.field2 !== prevProps.field2) {
      // field1 or field2 has changed. update field3
      this.props.input.onChange('new value goes here')
    }
  }

  render() {
    // your input here
  }
}

export default formValues('field1', 'field2')(Field3);

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