我试图保留用户可以从单选按钮中选择的页面背景。背景随所选选项而变化,但当我重新加载页面时它不会保留其值,并且它也不会应用任何指定的颜色,而是应用来自 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/