“警告:道具类型失败”当使用带有redux形式的react-datepikcer时

时间:2019-02-15 17:45:55

标签: reactjs redux redux-form react-datepicker

我在“ redux-form”旁边使用“ react-datepicker”,并且在控制台中不断出现此错误...

Warning: Failed prop type: Invalid prop `selected` of type `String` supplied to `DatePicker`, expected instance of `Date`.

新版本的“ react-datepicker”未使用“ moment()”,因此我发现的解决方案不起作用。

这是我的表单组件的外观...

import React, { Component } from "react";
import { compose } from "redux";
import { connect } from "react-redux";
import { reduxForm, Field } from "redux-form";
import DateInput from "../../form/DateInput";
import { subDays } from "date-fns";
import {
    combineValidators,
    isRequired
} from "revalidate";

class SignUpForm extends Component {
    onFormSubmit = values => {
        console.log(values);
    };

    render() {
        const { invalid, submitting, pristine } = this.props;
        return (
            <form onSubmit={this.props.handleSubmit(this.onFormSubmit)}>
                <Field
                    name="birthdate"
                    component={DateInput}
                    label="Birth Date"
                    dateFormat="yyyy-MM-dd"
                    showMonthDropdown
                    showYearDropdown
                    dropdownMode="select"
                    maxDate={subDays(new Date(), 366 * 18)}
                    showDisabledMonthNavigation
                />

                <Button
                    disabled={invalid || submitting || pristine}
                    type="submit"
                    size="big"
                    theme="black"
                >
                    Sign In
                </Button>
            </form>
        );
    }
}

const validate = combineValidators({
    birthdate: isRequired({ message: "Please choose your date of birth." })
});

export default compose(
    connect(
        null,
        actions
    ),
    reduxForm({ form: "signupForm", enableReinitialize: true, validate })
)(SignUpForm);

这是“ DateInput”组件的外观……

import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

const DateInput = ({
    input: { value, onChange, ...restInput },
    label,
    meta: { touched, error, dirty },
    ...props
}) => {
    let groupClasses = touched && !!error ? "input-group error" : "input-group";

    return (
        <div className={groupClasses}>
            <DatePicker
                {...props}
                selected={value ? value : null}
                onChange={onChange}
                {...restInput}
            />
            {touched && !!error && <span className="error">{error}</span>}
        </div>
    );
};

export default DateInput;

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

提供给value道具的selected似乎是不正确的格式。该值可能是redux-form提供的字符串。如果格式正确,则可以使用以下字符串创建日期:new Date(value)

selected={value ? new Date(value) : null}

您还可以使用redux-form提供的parse功能。