繁体   English   中英

React - useState 钩子访问状态

[英]React - useState hook access state

我有以下状态:

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

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

在下面的函数中,如果我点击上个月的某一天,我需要减少currentMonth statecurrentMonthsetCheckInMonth状态中设置currentMonth的新值。

问题是:

当我使用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()是异步的 它不会立即改变(更新)对象。 所以这样做 -

setCurrentMonth(currentMonth => currentMonth - 1);

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

你能做的是——

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

如果您想更新checkIn_month使用的当前值currentMonth ,你不能依靠currentMonth的价值立刻被更新,如setState调用是异步的。 您可以改为在传递给setCurrentMonth的回调中将您的调用移动到setCheckInMonth ,以便您可以访问currentMonth的当前值。

例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM