使用react-date和setState是不行的

时间:2018-05-01 07:56:41

标签: javascript reactjs state 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确实设置得很好。

我很困惑......

0 个答案:

没有答案