简体   繁体   中英

Using props.change to change the value of an input field in redux-form

I have a form that needs to retrieve the value of a field from my backend. It seems to retrieve the value successfully, but it does not update the value in the form.

How I use props.change to try to update field "foo":

const asyncValidate = (values, dispatch, props) => {
  return axios
  .get(URL)
  .then( (response) => {
    var whyNoChange = props.change("foo", response.data.foo)
    console.log(whyNoChange)
  });
}

Foo component:

const fooField = (props) => (
  <Form.Field 
  error={props.meta.touched && props.meta.error ? true : false}>
  <Input
      placeholder='Change me'
      onBlur={props.input.onBlur}
      onFocus={props.input.onFocus}
      onChange={(param, data) => props.input.onChange(data.value)}
      value={props.input.value}
  />
  {
    props.meta.touched && 
    props.meta.error && 
    <span style={{color: '#9f3a38'}}>
      {props.meta.error}
    </span>
  }
 </Form.Field>
)

My form:

 class MyForm extends Component { 
   // ...
   render () {
     return (
       <Form>
        <Field
         name='foo'
         component={fooField}
       />
      </Form>
   )
 }}

 MyForm = reduxForm({
   form: 'myform',
    validate,
    asyncValidate
 })(MyForm)

And finally what the console logs when it dispatches redux-form/change ...

{…}
 >meta: Object { form: "myform", field: "foo", touch: false, … }
  payload: "foo-from-backend"
  type: "@@redux-form/CHANGE"

But my foo-field value doesn't get updated. I checked the react developer tools and the value is just "". I followed the change directions as per the documentation . Any advice on where to go from here would be greatly appreciated. I am new to react and redux-form.

First of all, you have to dispatch it. Secondly, you are assigning a void function to a variable without calling it. Lastly, I believe that change accepts three arguments - form name , field name and value .

const asyncValidate = (values, dispatch, props) => {
  return axios
  .get(URL)
  .then( (response) => {
    dispatch(change("form name", "foo", response.data.foo))
  });
}

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