简体   繁体   中英

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. 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.

The problem seems to be that forceUpdate isn't triggering a reset of the component. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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