【问题标题】:How to initialize the redux-form with values from store如何使用 store 中的值初始化 redux-form
【发布时间】:2018-10-20 07:57:32
【问题描述】:

我正在尝试加载预先填充了来自商店的值的 Redux 表单。

目前,我可以直接使用 reducer 中的数据填充 redux 表单,但在提交表单时,它只接受可点击元素的数据以生成有效负载。

但是,我能够从 reducer 获取数据以进行存储。我需要用存储值初始化 redux 表单。

是否有任何最好的方法来使用存储中的值初始化表单元素并将整个模型作为有效负载提交?

我附上redux-form。

Redux 表单:-

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

let InitializeFromStateForm = props => {
  const { handleSubmit, pristine, reset, submitting } = props;
  return (
    <form onSubmit={handleSubmit}>
      <div>
        {/* <button type="button" onClick={() => load(data)}>Load Account</button> */}
      </div>
      <div>
        <label>First Name</label>
        <div>
          <Field
            name="first_Name"
            component="input"
            type="text"
            placeholder="First Name"
          />
        </div>
      </div>
      <div>
        <label>Last Name</label>
        <div>
          <Field
            name="last_Name"
            component="input"
            type="text"
            placeholder="Last Name"
          />
        </div>
      </div>


      <div>
        <button type="submit" >Submit</button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>
          Undo Changes
        </button>
      </div>
    </form>
  );
};

// Decorate with reduxForm(). It will read the initialValues prop provided by connect()
InitializeFromStateForm = reduxForm({
  form: 'initializeFromState', // a unique identifier for this form
})(InitializeFromStateForm);

// You have to connect() to any reducers that you wish to connect to yourself
InitializeFromStateForm = connect(
  state => ({
    initialValues: {'first_Name':'sunil','last_Name':'choudhary'}, // pull initial values from account reducer
  }),
//   { load: loadAccount }, // bind account loading action creator
)(InitializeFromStateForm);

export default InitializeFromStateForm;

【问题讨论】:

    标签: javascript reactjs redux react-redux redux-form


    【解决方案1】:

    change 函数让它变得如此简单...change 函数用于使用name 属性绑定Field 数据

    这是一个例子

    假设您在componentWillReceiveProps 中获取数据

    componentWillReceiveProps(nextProps) {
      const { change } = nextProps
      change('first_Name', 'sunil')
      change('last_Name', 'choudhary')
    }
    

    你可以找到更多here

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 2018-05-17
      • 2017-05-07
      相关资源
      最近更新 更多