javascript - 在 React.js 中挂载组件之前如何从本地存储加载状态?

标签 javascript reactjs local-storage

我试图保留用户可以从单选按钮中选择的页面背景。背景随所选选项而变化,但当我重新加载页面时它不会保留其值,并且它也不会应用任何指定的颜色,而是应用来自 className 的颜色,直到我单击其中一个单选按钮。

export default class App extends React.Component {
constructor(props) {
  super(props);

  this.state = {
    theme: true
  };
}

componentDidMount() {
  const theme = localStorage.getItem("theme");
  this.setState({ theme });
}

componentDidUpdate() {
  localStorage.setItem("theme", this.state.theme);
}

toggleTheme =() => {
  this.setState({
    theme: !this.state.theme
  });
}

render() {
  let bgStyle

  if(this.state.theme === true){
    bgStyle = {
      backgroundColor:"#3B3B3B",
    }
  }else if(this.state.theme === false){
    bgStyle={
      backgroundColor:"#ffffff",
    }
  }

  return (
    <div style={bgStyle} className="overall"></div>
  );
}
} 

切换背景颜色的代码在这里

class Menu extends React.Component {
    handleChange = (event) =>{
      this.props.toggleTheme();
  }
render() {
       <form>
          <label>
            <input
              type="radio"
              value="Dark"
              checked={this.props.theme === true}
              onChange={this.handleChange}
            />
            Dark
          </label>

          <label>
            <input
              type="radio"
              value="Light"
              checked={this.props.theme === false}
              onChange={this.handleChange}
            />
            Light
          </label>
        </form>
    );
  }
}

最佳答案

如果 boolean 值存储在本地存储中,它将作为 string 返回。

localStorage.getItem("theme"); -> "true"

它不符合您在 render 中的任何条件。它仅在您切换 radio 时有效,因为它被评估为 boolean - 感谢否定 (!):

!this.state.theme

解决方案:

解析本地存储的值。

const theme = JSON.parse(localStorage.getItem("theme"));

关于javascript - 在 React.js 中挂载组件之前如何从本地存储加载状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944043/

相关文章:

javascript - 如何在 React 16+ 中动态添加类?

javascript - 直接调用功能组件

google-chrome - 如何 "hide"chrome扩展本地存储

javascript - if else javascript 语句

javascript - 如何同步访问 indexedDB?

javascript - 如何使用 Javascript 切换多个 HTML 元素的背景颜色?

javascript - 从 localStorage 中提取数字作为数字

javascript - 将 require 与相对路径一起使用

javascript - 如何使用 Redux 存储中的数据渲染 React 组件

javascript - 如何在angularjs中访问$localStorage中保存的数据