You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React自定义日期选择器组件加载时不渲染,仅修改React Dev Tools状态才生效求助

问题原因
  • 违反React状态不可变原则:你直接修改dates状态的原数组(push、修改length),新旧数组引用完全一致,React的状态diff检测不到变化,因此不会触发重新渲染。你通过React DevTools修改状态时相当于强制触发了组件更新,才会加载已修改的数组内容。
  • useEffect依赖配置错误:你在useEffect的依赖数组中加入了dates,每次调用setDates都会触发useEffect重新执行,会导致无限循环问题。
  • 状态更新异步导致的初始值错误:setMonth、setYear是异步更新方法,调用后立即读取month、year拿到的还是旧值,首次执行getDatesInMonth时拿到的是初始默认的年月值,无法正确生成日期数组。
修复方案
  1. 移除useEffect依赖中的dates,仅保留month、year作为依赖
  2. 生成日期数组时创建新数组,不修改原状态数组,所有日期处理完成后再统一调用setDates更新状态
  3. 新增单独的初始化useEffect,仅在页面首次加载时执行一次,设置当前年月
  4. 移除循环中重复的setDates调用,减少不必要的性能消耗

修复后完整代码:

import { useState, useEffect } from 'react';

function App() {
  const [dates, setDates] = useState([]);
  // 补充month、year的初始状态定义
  const [month, setMonth] = useState(null);
  const [year, setYear] = useState(null);

  // 仅初始化执行一次,设置当前年月
  useEffect(() => {
    const d = new Date();
    setMonth(d.getMonth());
    setYear(d.getFullYear());
  }, []);

  // 年月变化时重新生成当月日期数组
  useEffect(() => {
    // 避免初始值为空时执行
    if (month === null || year === null) return;
    getDatesInMonth();
  }, [month, year]);

  // 获取指定月份的所有日期
  const getDatesInMonth = () => {
    const date = new Date(year, month);
    // 创建全新数组,不修改原状态
    const newDates = [];
    while (date.getMonth() === month) {
      newDates.push(new Date(date).toString());
      date.setDate(date.getDate() + 1);
    }
    // 统一更新状态
    setDates(newDates);
  }

  return (
    <div className="App">
      {dates.map((date, index) => (
        <h2 key={index}>{date}</h2>
      ))}
    </div>
  );
}

export default App;

内容的提问来源于stack exchange,提问作者Mehul Singh Rathore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:00:02