Javascript React-useState钩子访问状态
我有以下国家:Javascript React-useState钩子访问状态,javascript,reactjs,date,datepicker,calendar,Javascript,Reactjs,Date,Datepicker,Calendar,我有以下国家: let [currentMonth, setCurrentMonth] = useState(new Date().getMonth()); const [checkIn_month, setCheckInMonth] = useState(null); 我有一个点击事件监听器直接分配给JSX的元素tbody。使用事件委派单击td元素 在下面的函数中,如果我单击上个月的某一天,我需要减小currentmount状态,然后在setCheckInMonth状态中设置currentm
let [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [checkIn_month, setCheckInMonth] = useState(null);
我有一个点击事件监听器
直接分配给JSX的元素tbody
。使用事件委派
单击td元素
在下面的函数中,如果我单击上个月的某一天,我需要减小currentmount状态
,然后在setCheckInMonth
状态中设置currentmount
的新值
问题是:
当我使用setCheckInMonth(currentmount)
state钩子时,它给出的是旧值,而不是新值
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);
这是正确的做法吗?。它不会立即改变(更新)对象。因此,这样做—
setCurrentMonth(currentMonth => currentMonth - 1);
并不意味着currentmount
具有可在下一行中立即使用的更新值
你能做的是-
const newCurrentMonth = currentMonth - 1;
// now use this newCurrentMonth to update the state.
setCurrentMonth(newCurrentMonth );
setCheckInMonth(newCurrentMonth );
如果要使用当前值currentmount
更新checkIn\u month
,则不能依靠立即更新currentmount
的值,因为setState
调用是异步的。您可以在传递给setcurrentmount
的回调中将调用移动到setCheckInMonth
,这样您就可以访问currentmount
的当前值
例如:
setCurrentMonth(currentMonth=>{
const newcurrentmount=currentmount-1;
setCheckInMonth(newCurrentMonth);
返回newCurrentMonth;
});
您如何获得您的价值?你想从DOM中得到它吗?好的,那么我在问题中给出的最后一个答案是正确的<代码>设置当前月(当前月=>当前月-1)代码>设置签入月(当前月-1)代码>@grecdev,不能肯定。正如我在回答中提到的-setState
是异步的。因此,如果在某些情况下立即更新currentMonth,则checkInMonth
的值将错误。这种情况极不可能发生。但这在理论上是可以发生的。因此,我不建议采用这种方法。