Redux Form возвращает неожиданную ошибку с простой проверкой. Почему? - PullRequest
0 голосов
/ 08 октября 2019

Я создаю новую форму с помощью Redux Form, следуя этому простому примеру проверки формы Я получаю сообщение об ошибке, я не знаю, откуда оно приходит:

const renderTextField = ({
  input, label, meta: { touched, error }, children, type, placeholder,
}) => (
  <TextField
    className="material-form__field"
    label={label}
    type={type}
    error={touched && error}
    children={children}
    value={input.value}
    placeholder={placeholder}
    onChange={(e) => {
      e.preventDefault();
      input.onChange(e.target.value);
    }}
  />
);

renderTextField.propTypes = {
  input: PropTypes.shape().isRequired,
  label: PropTypes.string,
  meta: PropTypes.shape({
    touched: PropTypes.bool,
    error: PropTypes.string,
  }),
  children: PropTypes.arrayOf(PropTypes.element),
  type: PropTypes.string,
  placeholder: PropTypes.string,
};

renderTextField.defaultProps = {
  meta: null,
  label: '',
  children: [],
  type: 'input',
  placeholder: '',
};

const validate = (values) => {
  const errors = {};
  if (values.new_password_check !== values.new_password) {
    errors.new_password = 'ERROR';
  }
  console.log(errors);
  return errors;
};

class AccountSettings extends PureComponent {
  static propTypes = {
    handleSubmit: PropTypes.func.isRequired,
    reset: PropTypes.func.isRequired,
  };

  render() {
    const { handleSubmit, reset } = this.props;
    return (
      <form className="material-form" onSubmit={handleSubmit}>
        <div>
          <span className="material-form__label">Password (Optionnal)</span>
          <Field
            name="new_password"
            component={renderTextField}
            placeholder="Fill out this field only if you want to change your password"
            type="password"
          />
        </div>
        <div>
          <span className="material-form__label">Password Check (Optionnal)</span>
          <Field
            name="new_password_check"
            component={renderTextField}
            placeholder="Re-enter your new password for security reason if you wish to change it"
            type="password"
          />
        </div>
        <div>
          <span className="material-form__label">Current Password</span>
          <Field
            name="password"
            component={renderTextField}
            placeholder="Enter your current password to confirm the changes"
            type="password"
          />
        </div>
        <ButtonToolbar className="form__button-toolbar">
          <Button color="primary" type="submit">Update profile</Button>
          <Button type="button" onClick={reset}>
            Cancel
          </Button>
        </ButtonToolbar>
      </form>
    );
  }
}

export default reduxForm({
  form: 'profile_settings_form', // a unique identifier for this form
  validate, // <--- validation function given to redux-form
})(AccountSettings);

При попытке проверить values.new_password_check !== values.new_password, верно это или нет, я всегда получаю следующую ошибку в своей консоли:

Failed prop type: Invalid prop `error` of type `string` supplied to `ForwardRef(FormControl)`, expected `boolean`.

Я не делаю никаких propType для ошибки, и моя недавно созданная переменная ошибки - ошибки. Я действительно не понимаю, откуда это.

1 Ответ

2 голосов
/ 08 октября 2019

error должен быть логическим значением, а не строкой . Чтобы отобразить сообщение об ошибке, сделайте это вместо:

<TextField
    className="material-form__field"
    label={label}
    type={type}
    error={(touched && (typeof error !== 'undefined' && error != '')} // This says there is an error
    helperText={touched && error} // This will show the error message
    children={children}
    value={input.value}
    placeholder={placeholder}
    onChange={(e) => {
      e.preventDefault();
      input.onChange(e.target.value);
    }}
/>      
...