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

如何将选中主题保存到LocalStorage?React主题刷新重置问题修复

修复React主题刷新后重置的问题

问题根源

  1. 组件初始化时,从localStorage读取主题后,未同步更新document.documentElement的data-theme属性,导致页面样式仍为默认浅色
  2. 使用了React已弃用的componentWillMount生命周期方法
  3. 构造函数内theme的初始值逻辑错误,'theme'是永远为真的字符串,导致初始theme固定为dark,未考虑localStorage的初始状态

修复方案

直接修改代码如下,关键改动已标注:

class TodoList extends React.Component { 
  constructor(props) {    
    super(props);     
    // 从localStorage读取主题,无存储值则默认使用light
    const savedTheme = localStorage.getItem('theme');
    const initialTheme = savedTheme ? JSON.parse(savedTheme) : 'light';
    
    this.state = {    
      items: JSON.parse(localStorage.getItem('items')) || [],
      theme: initialTheme
    };
    // 初始化时立即将主题同步到DOM属性
    document.documentElement.setAttribute('data-theme', initialTheme);
    
    this.switchTheme = this.switchTheme.bind(this); 
    this.addItem = this.addItem.bind(this); 
    this.deleteItem = this.deleteItem.bind(this);
  }
  
  switchTheme() {
    const theme = this.state.theme === 'light' ? 'dark' : 'light';
    this.setState({ theme });
    document.documentElement.setAttribute('data-theme', theme);
  }

  addItem(e) {
   // 原有逻辑保持不变
  }

  deleteItem(key) {  
   // 原有逻辑保持不变
  }

  render() {
    return (
      // 原有JSX结构保持不变
      <button className='button-switch' onClick={this.switchTheme}>Switch theme</button>
    );
  }

  // 移除已弃用的componentWillMount,改用componentDidMount处理额外初始化逻辑
  componentDidMount() {
    // 可在此添加其他初始化操作,items已在构造函数中完成读取
  }
  
  componentDidUpdate() {
    localStorage.setItem('items', JSON.stringify(this.state.items));
    localStorage.setItem('theme', JSON.stringify(this.state.theme));
  }
}
export default TodoList;

关键改动说明

  • 构造函数初始化:直接从localStorage读取主题并处理空值情况,同时立即同步DOM的data-theme属性,确保页面加载时就应用正确主题
  • 移除弃用方法:删除已被React弃用的componentWillMount,将初始化逻辑移至构造函数更合规
  • 状态与DOM同步:确保主题变更(初始化或手动切换)时,state状态与DOM属性始终保持一致

内容的提问来源于stack exchange,提问作者Emily

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:42:08