如何将选中主题保存到LocalStorage?React主题刷新重置问题修复
修复React主题刷新后重置的问题
问题根源
- 组件初始化时,从localStorage读取主题后,未同步更新
document.documentElement的data-theme属性,导致页面样式仍为默认浅色 - 使用了React已弃用的
componentWillMount生命周期方法 - 构造函数内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
相关产品推荐
相关产品推荐

