日期设置在 React 中不起作用 "useState"
Date setting not working in react "useState"
我正在尝试使用 useState
钩子进行反应,作为默认值,我想设置一个传入的道具值 (startDate)。不幸的是,它总是设置在 actual/current 日期。我在这里弄错了什么?
我的代码:
export type CalendarProps = {
startDate: Date,
endDate: Date,
};
const SomeCalendarView: React.FC = (props: CalendarProps) => {
console.log(props.startDate);
const [selectedDay, setSelectedDay] = useState(props.startDate);
console.log(selectedDay);
....
我的控制台日志:
5 月 12 日 - 是我的开始日期。
5 月 14 日 - 是我现在的 date/time。
为什么我得到的是实际时间?有什么想法吗?
我不知道,我的 props 日期(startDate
和 endDate
)有延迟,useState
默认值立即获得价值(因为 props日期不可用,它填充了 actual/current 日期)。一旦道具发生变化,我必须使用 useEffect
来设置我的状态。喜欢这里:
const [selectedDay, setSelectedDay] = useState();
const [selectedStage, setSelectedStage] = useState();
useEffect(
() => {
setSelectedDay(props.startDate);
setSelectedStage(props.stages.valueSeq().first());
},
[props.startDate, props.stages],
);
我正在尝试使用 useState
钩子进行反应,作为默认值,我想设置一个传入的道具值 (startDate)。不幸的是,它总是设置在 actual/current 日期。我在这里弄错了什么?
我的代码:
export type CalendarProps = {
startDate: Date,
endDate: Date,
};
const SomeCalendarView: React.FC = (props: CalendarProps) => {
console.log(props.startDate);
const [selectedDay, setSelectedDay] = useState(props.startDate);
console.log(selectedDay);
....
我的控制台日志:
5 月 12 日 - 是我的开始日期。
5 月 14 日 - 是我现在的 date/time。
为什么我得到的是实际时间?有什么想法吗?
我不知道,我的 props 日期(startDate
和 endDate
)有延迟,useState
默认值立即获得价值(因为 props日期不可用,它填充了 actual/current 日期)。一旦道具发生变化,我必须使用 useEffect
来设置我的状态。喜欢这里:
const [selectedDay, setSelectedDay] = useState();
const [selectedStage, setSelectedStage] = useState();
useEffect(
() => {
setSelectedDay(props.startDate);
setSelectedStage(props.stages.valueSeq().first());
},
[props.startDate, props.stages],
);