传递动态表单值redux-form

时间:2017-11-20 14:00:30

标签: reactjs redux react-redux redux-form

我有一个名为profileDetails的道具,我想用它来设置表格值。是一种以redux形式动态添加多个表单值的方法吗?

我尝试了values: this.props.profileDetailsvalues: profileDetails我得到了Uncaught ReferenceError: <variable> is not defined

编辑:我尝试在values: ...中使用initialValues: ...reduxForm({})

import React from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import { InputField } from '~/shared/components/formFields';

const ProfileEditComponent = ({
  handleSubmit,
  profileDetails,
 }) => (
  <form onSubmit={handleSubmit} className="form-horizontal">
  <Field
    name="first_name"
    type="text"
    component={InputField}
    label="First Name"
    labelClass="col-sm-2"
    inputDivClass="col-sm-10"
    value={profileDetails.first_name}
  />
  </form>
);

export default reduxForm({
  form: 'profile-edit-form',
  destroyOnUnmount: false,
  enableReinitialize: true,
  value: profileDetails // <-- how do I pass profileDetails dynamically?
})(ProfileEditComponent);


// Input component

import React from 'react';
import PropTypes from 'prop-types';

const InputField = ({ ...props }) => (
  <div className="form-group">
    <label
      htmlFor={props.input.name}
      id={props.input.name}
      className={props.labelClass}
    >
      {props.label}
    </label>
    <div className={props.inputDivClass}>
      <input
        type={props.type}
        name={props.input.name}
        className="form-control"
        value={props.input.value}
        {...props.input}
      />
    </div>
  </div>
);

InputField.propTypes = {
  type: PropTypes.string,
  name: PropTypes.string,
  value: PropTypes.string,
  input: PropTypes.shape(),
  label: PropTypes.string,
  labelClass: PropTypes.string,
  inputDivClass: PropTypes.string,
};

InputField.defaultProps = {
  type: '',
  name: undefined,
  value: undefined,
  input: {},
  label: '',
  labelClass: '',
  inputDivClass: '',
};

export default InputField;

2 个答案:

答案 0 :(得分:3)

您需要像使用redux格式一样初始化表单,并且必须连接()您的表单与reducers中的数据。

这样的事情:

const InitializeProfileEditComponent = reduxForm({
  form: 'profile-edit-form',
  destroyOnUnmount: false,
  enableReinitialize: true,
})(ProfileEditComponent);

const ProfileEditForm = connect(
  state => ({
    initialValues: state.profileDetail, // state in your redux store
  })
)(InitializeProfileEditComponent)

export default ProfileEditForm;

我希望这可以帮助你https://redux-form.com/7.1.2/examples/initializefromstate/

答案 1 :(得分:1)

如果你已经知道要以哪种形式放入什么值,你可以使用redux-form中的initialValues。

在你的情况下,你想要一个道具作为价值,所以你需要通过mapStateToProps传递它

像这样:

function mapStateToProps(state, ownProps) {
  return {
    initialValues: {
      first_name: ownProps.propThatHasFirstName
    }
}


export default reduxForm({
  form: 'profile-edit-form',
  destroyOnUnmount: false,
  enableReinitialize: true,
})(ProfileEditComponent);