繁体   English   中英

使用带有redux-form的react-datepicker

[英]Using react-datepicker with redux-form

我正在尝试使用带有redux-form的react-datepicker,我正面临一个问题。 当我从日期选择器中选择日期时,我收到以下错误:

Uncaught TypeError: t.isSame is not a function

我的代码如下:

// My component that uses the date picker
const renderDateField = (field) => {
  return (
    <div>
      <img src={require('./images/date.png')} className={styles.iconField} />
      <DatePicker {...field.input} placeholderText={field.placeholder} onChange={field.onDateChange} dateFormat='DD/MM/YYYY' selected={field.selected ? field.selected : null} className={styles.inputField} />
    </div>
  );
};

export class MyComponent extends React.Component {

  constructor (props) {
    super(props);
    this.state = {
      startDate: moment()
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange (date) {
    console.log('handle Change', date);
    this.setState({
      startDate: date.format('DD/MM/YYYY')
    });
  }

  render () {
    const { handleSubmit } = this.props;
    console.log('Render global state.startDate', this.state.startDate);
    return (
      <div>
        <form onSubmit={handleSubmit(this.props.filterSubmit)} method='post' action='/tennis/search'>
                ...
                <Field name='date' placeholder='Quand ?' component={renderDateField} onDateChange={this.handleChange} selected={this.state.startDate} />
                ...
        </form>
      </div>)
    ;
  }
}
...
TennisSearchFilters.propTypes = {
  filters: React.PropTypes.shape({
    date: React.PropTypes.object
  }),
  filterSubmit: React.PropTypes.func.isRequired,
  handleSubmit: propTypes.handleSubmit
};
    ...
export default reduxForm({
          form: 'tennisSearch',
          validate: validateTennisSearchForm
        })(TennisSearchFilters);

我认为存在格式错误,因为输入值似乎更新为字符串,然后在将时刻与字符串进行比较时崩溃。 但我不太确定...所以我请求你的帮助:)

我检查了其他人关于它的帖子和问题,但它没有正常工作(也许我做错了但是)。

非常感谢你的帮助!

看看提供的代码示例,我假设react-datepicker正在使用moment

onChange方法接收moment实例,您将此实例转换为纯字符串。 然后, react-datepicker isSame尝试在字符串值上调用isSame方法,这当然会失败。

而不是将更新的值转换为字符串,而是按原样存储。

this.setState({
    startDate: date,
});

试试你的日历组件::

 onChange ={val => {
   field.onDateChange // Rather read the value from redux-form
   return field.input.onChange(val) // This should dispatch the value to redux-form
  }
}

在使用redux-form时,不确定为什么要在此处设置其他视图状态?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM