[英]React - useState hook access state
我有以下状态:
let [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [checkIn_month, setCheckInMonth] = useState(null);
我有一个直接分配给JSX's
元素tbody
的click event listener
。 使用event delegation
点击td elements
。
在下面的函数中,如果我点击上个月的某一天,我需要减少currentMonth state
, currentMonth
在setCheckInMonth
状态中设置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.