简体   繁体   English

似乎无法在React中重置组件状态

[英]Can't seem to reset component state in React

I'm trying to reset the date value/text inside react-datepicker when user enters an invalid date. 当用户输入无效的日期时,我正在尝试重置react-datepicker中的日期值/文本。 Here is the code: 这是代码:

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: Date.now()
    };
  }

  render() {
    return (
      <DatePicker
        name="date"
        selected={this.state.date && moment(this.state.date, "x")}
        onChange={date => {
          this.setState({
            date: date.valueOf()
          });
        }}
        onBlur={e => {
          let date = moment(e.target.value, "LLL", true);
          if (date.isValid()) {
            this.setState({
              date: date.valueOf() // apply good value
            });
          } else {
            this.forceUpdate();
          }
        }}
        showTimeSelect
        timeFormat="HH:mm"
        timeIntervals={30}
        dateFormat="LLL"
        timeCaption="Time"
        minDate={moment().add(30, "minutes")}
      />
    );
  }
}

I tried to put it into JSFiddle but it seems to be having trouble with rendering react-datepicker component, yet this component renders fine in my own code. 我试图将其放入JSFiddle,但是在渲染react-datepicker组件时似乎遇到了麻烦,但是该组件在我自己的代码中可以正常渲染。

The problem seems to be that forceUpdate isn't triggering a reset of the component. 问题似乎是forceUpdate不会触发组件的重置。 I'm wondering if the reset only occurs to the calendar selection itself and not the input field (which is what I'm trying to do). 我想知道是否重置仅发生在日历选择本身而不是输入字段上(这是我要尝试的操作)。 I tried adding value property and setting it to the same thing as selected property but it has no effect. 我尝试添加value属性并将其设置为与selected属性相同的东西,但是没有效果。 The validation is firing and working as expected, but the rerendering on the input field text is not. 验证可以正常进行,并且可以正常工作,但输入字段文本上的重新呈现却没有。

There is no need to force the update of the component if the state isn't changed and, if the state change, the view will be rendered again anyway. 如果状态未更改,则无需强制更新组件;如果状态更改,则无论如何将再次呈现视图。 Forcing updates like that will result in no changes in render. 像这样强制更新将不会导致渲染发生任何变化。 Usually when formatting dates with moment I check first that raw data is suitable to be converted in a date, then I convert it and I've never needed to check it again. 通常在格式化日期时,我会先检查原始数据是否适合转换为日期,然后再进行转换,而无需再次检查。

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

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