我正在尝试保留用户可以从单选按钮选择的页面背景。背景随选定的选项而变化,但是当我重新加载页面时它不会保留其值,它也不会应用任何指定的颜色,而是应用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中的任何条件都不匹配。它仅在您切换收音机时有效,因为它的求值为boolean-由于取反(!):

!this.state.theme


解:

解析本地存储中的值。

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

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

10-12 00:40
查看更多