我的应用程序具有动态路由(动态路由参数),其中包含redux表单。为了区分表单数据,我需要将redux表单数据与react route参数一起发布。

我已经将react route param作为道具从父组件传递到具有redux形式的子组件,即props中的初始值具有param值。我想使用隐藏类型将route param初始化为输入字段。

import React from 'react';
import { Field, reduxForm,propTypes } from 'redux-form';
import submit from '../actions/commentActions'
import connect from 'react-redux';
const validate = values => {
  const errors = {}
  if (!values.email) {
    errors.email = 'Required'
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address'
  }

  if (!values.message) {
    errors.message = 'Required !!'
  }else if (values.message.length > 15) {
    errors.message = 'Must be 15 characters or less'
  }
  return errors
}

const renderField = ({
  input,
  label,
  type,
  meta: { touched, error, warning }
}) => (
  <div>
    <div>
      <input {...input} placeholder={label} type={type} className="form-control" />
      {touched &&
        ((error && <span className="text-danger">{error}</span>) )}
    </div>
  </div>
)

const renderTextAreaField = ({
  input,
  label,
  type,
  meta: { touched, error, warning }
}) => (
  <div>
    <div>
      <textarea {...input} rows="3" placeholder={label}
      className="form-control shareThought mt-1"></textarea>
      {touched &&
        ((error && <span className="text-danger">{error}</span>) )}
    </div>
  </div>
)

const AddComment = props => {
  const { error,handleSubmit, pristine, reset, submitting,initialValues } = props;
  // console.log(initialValues); prints route param i.e honda
  // console.log(props);

  return (
      <div className="leaveComment pb-2">
        <form onSubmit={handleSubmit(submit)}>
            <Field
              name="email"
              component={renderField}
              type="email"
              label="Email Id"
              placeholder="Enter Email"
            />

            <Field name="message"
             component={renderTextAreaField}
             label="Share Your thought"
             type="text"
             />

            <Field name="modelname"
             type="text"
             component="input"
             value={initialValues}
             hidden
             />

             <span className="text-danger">{error && <span>{error}</span>}</span>

            <div className="row mx-0" >
              <button type="submit" className="btn btn-sm btn-info btn-block mt-2" disabled={pristine || submitting}>Leave a comment</button>
            </div>
        </form>
      </div>
  );
};

export default reduxForm({
  form: 'addcommentmsg',
  validate
})(AddComment);

最佳答案

我通过为键值传递initialValues解决了这个问题

let initialValues = {
        initialValues: {
          modelname: this.props.pageId
        }
    };


因此,您不必在输入字段或prop中定义initialValues

关于javascript - 警告: Prop 类型失败:提供给Form(AddComment)的 Prop 无效的“initialValues”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47221001/

10-11 14:47