以 redux 形式在字段中设置值 [英] Set value in field in redux form

查看:38
本文介绍了以 redux 形式在字段中设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有下拉菜单和文本字段的 redux 表单.在下拉更改时,我必须更新其他字段.其他字段使用自定义组件示例

I have redux form having dropdown and text fields. On dropdown change i have to update the other fields. The other fields are using custom component example

所以结构是这样的.1. 有形的组件2. 字段组件.

So the structure is like. 1. component having form 2. Field component.

现在我用谷歌搜索并发现很少有东西可以更新该字段,但无法做到.我试过的1.在字段中添加状态,如下所示.不起作用.

Now i googled and found few things to update the field but not able to do it. What i tried 1. Adding state in the field like below in value. Does not work.

<Field name="accountno" value="this.state.accountno" component={InputText} placeholder="Number" />

  1. 试过disptach,但无法使用.因没有派遣 i 道具类型而出错

  1. Tried disptach but not able to use it. Getting error for no dispatch i prop type

this.props.dispatch(change('form', 'accountno', 'test value'));

this.props.dispatch(change('form', 'accountno', 'test value'));

尝试过 this.props.fields,但与 props 类型中的字段不同.

Tried this.props.fields but same not fields in props type.

它应该可以使用 2 或 3,但无法找到添加它们的位置.请让我知道如何使用这些或任何其他方式.

It should work using 2 or 3 but not able to find where to add those. Please let me know how can i use these or any other way.

推荐答案

使用 redux-form 时,不需要直接在字段中设置值.您可以使用 initialize 方法来填充表单.或者 initialValues 作为传递给 redux 的对象的属性来映射 state 到 props.另一种方法是使用 redux-form 中的函数 change 单独设置值.为了使其工作,您需要使用 react-redux 中的 connect 包装您的组件.它在你的 props 中嵌入了 dispatch 方法.

When using redux-form, you don't need to set the value directly into the field. You can use the method initialize to populate your form. Or initialValues as a property of the object passed to redux to map state to props. The other way is to set the values individually using the function change from redux-form. In order to make it to work, you need to wrap your component with connect from react-redux. It embeds the dispatch method in your props.

import React, { Component } from 'react';
import { reduxForm, Field, change } from 'redux-form';
import { connect } from 'react-redux';

class Form extends Component {
  componentDidMount() {
    this.props.initialize({ accountno: 'some value here' });
    // set the value individually
    this.props.dispatch(change('myFormName', 'anotherField', 'value'));
  }

  render() {
    return (
      <form onSubmit={...}>
        ...
        <Field name="accountno" component={InputText} placeholder="Number" />
        <Field name="anotherField" component={InputText} />
      </form>
    )
  }
}

Form = reduxForm({ 
  form: 'myFormName' 
})(Form);

export default connect(state => ({ 
  // alternatively, you can set initial values here...
  initialValues: {
    accountno: 'some value here'
  } 
}))(Form);

这篇关于以 redux 形式在字段中设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆