我有以下状态:
let [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [checkIn_month, setCheckInMonth] = useState(null);
我在JSX
元素tbody
上直接分配了click事件监听器
,并使用事件委托
来点击td元素
。
在以下函数中,如果我点击上一个月份中的某一天,我需要将currentMonth状态
减少,并在setCheckInMonth
状态中设置新值。
问题是:
当我使用setCheckInMonth(currentMonth)
状态钩子时,它会给出旧值而不是新值。
let [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [checkIn_month, setCheckInMonth] = useState(null);
const selectDate = e => {
if (e.target.tagName === 'TD') {
if (e.target.classList.contains('previous-month-day')) {
setCurrentMonth(currentMonth => currentMonth - 1);
setCheckInMonth(currentMonth);
}
}
}
如果我做类似这样的事情会怎么样:
setCurrentMonth(currentMonth => currentMonth - 1);
setCheckInMonth(currentMonth - 1);
这是一个正确的方法吗?