问题描述
这是我的密码
import format from "date-fns/format";
import setHours from "date-fns/setHours";
import setMinutes from "date-fns/setMinutes";
const [startDate,setStartDate] = useState<Date>(new Date());
const startTime = setHours(setMinutes(date,0),hour);
console.log(startTime); // showing correct date and time as I set
setStartDate(startTime);
console.log(startDate); // this is showing current date and time
但是当我这样做
console.log(startDate);
我得到当前日期和时间。但是如果我这样做
console.log(startTime);
它显示我想要的正确日期和时间。
请您帮忙。我正在使用React的tsx格式。开发人员再过几个小时都无法使用,因此我必须尽快将其交付给客户。
解决方法
useState
是一个异步函数。在您尝试读取状态时,它正在执行中,其值尚未更新。考虑以下示例:
//Defining the state
const [startDate,setStartDate] = useState<Date>(new Date());
const startTime = setHours(setMinutes(date,0),hour); //Calculating new state
console.log(startTime); // Works fine due to synchronouse behaviour
setStartDate(startTime); //Async,will wait if any other state updates are in pipeline. If not,it'll try to update asynchronously
console.log(startDate); // By the time you reach here it's still updating and pointing to the old value.
如果要读取新值,可以考虑使用useEffect(fn,[])
。就您而言,您可以阅读以下新状态:
const [startDate,setStartDate] = useState<Date>(new Date());
useEffect(()=>{
console.log(startDate); // Fires whenever startDate changes
},[startDate])
您可以在此处访问codesandbox进行演示。另外,您可以阅读有关useEffect
here和here [详细]
在最后两行中您做错了
setStartDate(startTime);
console.log(startDate);
如果将startDate设置为startTime,它将最终向您显示当前日期和时间。希望它能起作用