如何使用store中的值初始化redux-form

时间:2018-05-10 05:44:31

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

我尝试加载预先填充了商店值的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;

1 个答案:

答案 0 :(得分:0)

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

以下是执行此操作的示例

假设您在componentWillReceiveProps

中获取了数据
componentWillReceiveProps(nextProps) {
  const { change } = nextProps
  change('first_Name', 'sunil')
  change('last_Name', 'choudhary')
}

你可以找到更多here