React - useState 钩子访问状态

React - useState hook access state

我有以下状态:

let [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [checkIn_month, setCheckInMonth] = useState(null);

我有一个 click event listener 直接 分配给 JSX's 元素 tbody。使用 event delegation 点击 td elements.

并且在下面的函数中,如果我点击 上个月 的某一天,我需要递减 currentMonth state 然后设置新值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);

这是正确的做法吗?

setState() is asynchronous。它不会立即改变(更新)对象。所以这样做 -

setCurrentMonth(currentMonth => currentMonth - 1);

并不意味着 currentMonth 具有您可以在下一行中立即使用的更新值。

你能做的是 -

const newCurrentMonth = currentMonth - 1;
// now use this newCurrentMonth to update the state.
setCurrentMonth(newCurrentMonth );
setCheckInMonth(newCurrentMonth );

如果您想使用 currentMonth 的当前值更新 checkIn_month,您不能依赖 currentMonth 的值立即更新,因为 setState调用是异步的。您可以改为在传递给 setCurrentMonth 的回调中将调用移至 setCheckInMonth,以便您可以访问 currentMonth.

的当前值

例如:

setCurrentMonth(currentMonth => {
    const newCurrentMonth = currentMonth - 1;
    setCheckInMonth(newCurrentMonth);
    return newCurrentMonth;
});