我正在尝试实施取消功能,如果用户点击反应日期日期选择器日历之外会发生某些事情。
在我的日历组件中,我设置了两个属性的状态 - startDate
和endDate
,但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
确实设置得很好。
我很困惑......