0

我正在尝试实现取消功能,如果用户在 react-dates 日期选择器日历之外单击,则会发生某些事情。

在我的日历组件中,我正在为两个属性设置状态 -startDateendDate没有endDate在状态上设置。如果我添加断点,我可以看到它会命中并尝试用一个值设置它。如果我为正在更新的状态添加回调函数,这永远不会运行,所以发生了一些我无法解决的奇怪事情。

为什么状态不更新?控制台中没有错误。

我的日历组件中的示例代码:

onDatesChange = ({ startDate, endDate }) => {
    this.setState({ startDate, endDate });
    if (startDate && endDate) {
        this.props.onDatesPicked(startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD'));
    }
};

onClose = () => {
    const { startDate, endDate } = this.state;
    if (!startDate || !endDate) {
        this.props.onCancel();
    }
};

render() {
    const { startDate, endDate, focusedInput } = this.state;

    return (
        <div className={css.component}>
            <DateRangePicker
                displayFormat="DD MMM YYYY"
                isOutsideRange={this.isOutsideRange}
                startDate={startDate}
                startDateId={START_DATE}
                startDatePlaceholderText="Start date"
                endDate={endDate}
                endDateId={END_DATE}
                endDatePlaceholderText="End date"
                onDatesChange={this.onDatesChange}
                focusedInput={focusedInput}
                onFocusChange={this.onFocusChange}
                firstDayOfWeek={1}
                hideKeyboardShortcutsPanel
                minimumNights={0}
                withPortal
                onClose={this.onClose}
            />
        </div>
    );
}

onClose函数中永远找不到值,endDate即使setState已经被调用onDatesChange并传入了一个值。没有问题startDate。如果我注释掉设置,startDate那么endDate设置得很好。

我感到很困惑...

4

0 回答 0