[英]React - useState hook access state
I have the following states:我有以下状态:
let [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [checkIn_month, setCheckInMonth] = useState(null);
I have an click event listener
assigned directly to JSX's
element tbody
.我有一个直接分配给
JSX's
元素tbody
的click event listener
。 Using event delegation
to click on the td elements
.使用
event delegation
点击td elements
。
And in the following function if i click on a day that is in the previous month i need to decrement the currentMonth state
and after that to set the new value of currentMonth
in the setCheckInMonth
state.在下面的函数中,如果我点击上个月的某一天,我需要减少
currentMonth state
, currentMonth
在setCheckInMonth
状态中设置currentMonth
的新值。
The problem is:问题是:
When i use the setCheckInMonth(currentMonth)
state hook it gives the old value, not the new one.当我使用
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);
}
}
}
What if i do something like this:如果我做这样的事情怎么办:
setCurrentMonth(currentMonth => currentMonth - 1);
setCheckInMonth(currentMonth - 1);
Is this a correct way of doing it ?这是正确的做法吗?
setState()
is asynchronous . setState()
是异步的。 It doesn't immediately mutate(update) the object.它不会立即改变(更新)对象。 So doing this -
所以这样做 -
setCurrentMonth(currentMonth => currentMonth - 1);
doesn't mean that currentMonth
has the updated value that you can use immediately in the next line.并不意味着
currentMonth
具有您可以在下一行立即使用的更新值。
What you can do is -你能做的是——
const newCurrentMonth = currentMonth - 1;
// now use this newCurrentMonth to update the state.
setCurrentMonth(newCurrentMonth );
setCheckInMonth(newCurrentMonth );
If you want to update checkIn_month
using the current value of currentMonth
, you can't rely on currentMonth
's value being updated immediately, as setState
calls are asynchronous.如果您想更新
checkIn_month
使用的当前值currentMonth
,你不能依靠currentMonth
的价值立刻被更新,如setState
调用是异步的。 You can instead move your call to setCheckInMonth
within the callback passed to setCurrentMonth
so that you have access to the current value of currentMonth
.您可以改为在传递给
setCurrentMonth
的回调中将您的调用移动到setCheckInMonth
,以便您可以访问currentMonth
的当前值。
For example:例如:
setCurrentMonth(currentMonth => {
const newCurrentMonth = currentMonth - 1;
setCheckInMonth(newCurrentMonth);
return newCurrentMonth;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.