React - useState 钩子如何访问状态

3

我有以下状态:

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);

这是一个正确的方法吗?


你如何获取你的值?你是试图从DOM中获取它吗? - jbergeron
2个回答

2

setState()是异步的,它不会立即改变(更新)对象。因此,执行以下操作 -

setCurrentMonth(currentMonth => currentMonth - 1);

这并不意味着currentMonth已经更新了数值,可以立即在下一行使用。

你可以这样做 -

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

那么我在问题中发布的最后一个答案是正确的吗?setCurrentMonth(currentMonth => currentMonth - 1); setCheckInMonth(currentMonth - 1); - user11910832
@grecdev 这个很难说。就像我在回答中提到的,setState 是异步的。因此,如果在某些情况下 currentMonth 立即更新,那么 checkInMonth 就会有错误的值。虽然这种情况非常不可能发生,但从理论上讲它是存在的。所以我不建议采用这种方法。 - Arnab Roy

0
如果您想使用currentMonth的当前值来更新checkIn_month,则不能依赖于currentMonth的值立即更新,因为setState调用是异步的。相反,您可以将对setCheckInMonth的调用移动到传递给setCurrentMonth的回调函数中,以便您可以访问currentMonth的当前值。
例如:
setCurrentMonth(currentMonth => {
    const newCurrentMonth = currentMonth - 1;
    setCheckInMonth(newCurrentMonth);
    return newCurrentMonth;
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接