使用DayJS初始化React组件日期状态时出现错误日期问题
日期状态初始化异常问题
我在项目中使用DayJS库,向GanttChartOrders组件传递两个日期props,但组件内部初始化的日期状态出现错误。
服务器返回的日期数据:
horizontStart: '2025-01-29T00:00:00Z' horizontEnd: '2025-04-01T00:00:00Z'
父组件传递props的代码:
<GanttChartOrders horizontStart={new Date(gantt?.horizont_start || new Date(new Date().getFullYear(), 0, 1))} horizontEnd={new Date(gantt?.horizont_end || new Date())} data={gantt || []} isTooltip={true} tooltip={tooltip} inferringId={inferringId} filterType={filterType} ganttType={ganttType} />
在GanttChartOrders组件内,我通过useState结合DayJS初始化状态:
const [initialStart, setInitialStart] = useState(dayjs(horizontStart)) const [initialEnd, setInitialEnd] = useState(dayjs(horizontEnd))
但initialEnd被初始化为今日日期,状态始终使用首次渲染的默认值,没有随传入的props更新。不过console.log能看到正确的props值:
日志输出:
Wed Jan 29 2025 03:00:00 GMT+0300 (Moscow Standard Time) Tue Apr 01 2025 03:00:00 GMT+0300 (Moscow Standard Time) M2 {$L: 'en', $u: undefined, $d: Wed Jan 01 2025 00:00:00 GMT+0300 (Moscow Standard Time), $y: 2025, $M: 0, …} M2 {$L: 'en', $u: undefined, $d: Tue Mar 04 2025 18:18:41 GMT+0300 (Moscow Standard Time), $y: 2025, $M: 2, …}
问题原因
- useState初始值特性:useState的初始参数仅在组件首次渲染时生效,后续props更新不会自动同步到状态中。
- 首次渲染默认值触发:父组件中
gantt数据可能是异步加载的,首次渲染时gantt?.horizont_end为undefined,导致horizontEnd使用了默认值new Date(),此时initialEnd被初始化为今日日期。后续gantt加载完成后props更新,但状态未同步。
解决方案
方案1:用useEffect监听props变化同步状态
在GanttChartOrders组件中添加useEffect,监听horizontStart和horizontEnd的变化,更新状态:
const [initialStart, setInitialStart] = useState(dayjs(horizontStart)) const [initialEnd, setInitialEnd] = useState(dayjs(horizontEnd)) // 监听props变化,同步状态 useEffect(() => { setInitialStart(dayjs(horizontStart)) setInitialEnd(dayjs(horizontEnd)) }, [horizontStart, horizontEnd])
方案2:直接使用props,不存状态
如果这两个日期不需要在组件内部修改,直接使用传入的horizontStart和horizontEnd即可,无需用useState存储。
方案3:确保首次渲染时props已有正确值
调整父组件逻辑,等待gantt数据加载完成后再渲染GanttChartOrders组件,避免首次渲染使用默认值:
{gantt && ( <GanttChartOrders horizontStart={new Date(gantt.horizont_start)} horizontEnd={new Date(gantt.horizont_end)} // 其他props... /> )}
内容的提问来源于stack exchange,提问作者David Abramov
相关产品推荐
相关产品推荐

