0

我将 react-dates 用于日期选择器,当用户更改日期时,它会更新道具并将其发送到后端以作为查询中的参数运行,以从数据库中获取当天的特定结果。它看起来像这样:

    class TableComponent extends Component {
    constructor(props) {
    super(props);

    this.columnDefs = columnDefs;
    this.state = {
      isLoading: true,
      showTimeoutPopup: false,
      tableData: [],
      currentDate: this.props.currentDate
     };
    }

    componentDidMount() {
       this.fetchData();
     }

    componentDidUpdate(prevProps) {
      if (`${this.props.currentDate}` !== prevProps.currentDate) {
        this.fetchData(this.props.currentDate);
      }
    }

    fetchData() {
      this.setState({
        isLoading: true
      });

    someApi.getData(this.props.currentDate).then(tableData => this.setState({
      tableData: tableData,
      isLoading: false
    }))
      .catch(error => {
        if (error.message === 'timeout') {
          this.setState({
            showTimeoutPopup: true
          });
        } else {
          throw new Error(error.message);
        }
      });
    }

这在使用日期选择器通过 UI 选择日期时有效。当我尝试输入日期时,它会崩溃,因为当我输入第一个数字时,比如 2019 年 12 月 23 日月份的 1,它会在 API 请求中发送该 1,但由于日期无效而失败。但是,如果我粘贴整个日期,它将在获得正确日期时起作用。有没有更好的替代 componentDidUpdate 或更好的方法来构造这种类型的请求?我需要它等到输入整个日期后再发送请求。我也不一定要单击按钮,我希望它在日期选择器的文本框中完成所有操作。如果这里重要的是 datepicker 组件:

  class DatePicker extends Component {
    constructor(props) {
      super(props);
      this.state = {
        currentDate: this.props.currentDate,
        focused: false
      };
    }

    componentDidUpdate(prevProps) {
      if (prevProps.currentDate !== this.props.currentDate) {
        this.setState({currentDate: this.props.currentDate});
      }
    }

    render() {
      return (
        <div className="form-group">
          <label className="tuxedo_label">Select or enter a date to view error reports for that 
           day</label>
          <div className="input_feedback">Dates should be in the format MM/DD/YYYY</div>
          <SingleDatePicker
            date={this.state.currentDate}
            id="date_id"
            customInputIcon={
              <i className="icon calendar-o blue">
                <span className="sr-only">open calendar</span>
              </i>
            }
            displayFormat="MM/DD/YYYY"
            numberOfMonths={1}
            isOutsideRange={() => false}
           onDateChange={this.props.onDateChange}
            focused={this.state.focused}
            onFocusChange={({ focused }) => this.setState({ focused: focused })}
          />
        </div>
      );
    }
  }
4

1 回答 1

0

使用时刻来验证

npm install moment --save

import moment from 'moment';

componentDidUpdate(prevProps) {
      if (`${this.props.currentDate}` !== prevProps.currentDate && moment(this.props.currentDate).isValid()) {
          this.fetchData(this.props.currentDate);
      }
}
于 2019-12-23T17:33:27.363 回答