https://codesandbox.io/s/xrp56z04yq
getInitialState = () => {
var addFavirote = localStorage.getItem("AddFavirote") || 1;
console.log("getInitialState--->", addFavirote);
return {
addFavirote: addFavirote
};
//this.setState(state => ({ belowExpanded: !state.belowExpanded }));
};
<FavoriteIcon
style={{ display: this.state.addFavirote ? "none" : "" }}
onClick={e => {
console.log("favoriteEvent---.", e);
console.log(
"this.state.addFavirote---.",
this.state.addFavirote
);
localStorage.setItem("AddFavirote", !this.state.addFavirote);
this.setState({ addFavirote: !this.state.addFavirote });
console.log(
"!this.state.addFavirote---.",
!this.state.addFavirote
);
this.props.onAddBenchmark(this.props);
}}
/>
答案 0 :(得分:2)
从LocalStorage syntax文档中,您需要将addFavorite
序列化为字符串以设置为本地存储。在componentDidMount
上,当从localStorage检索值时,可以将其解析回getInitialState
中的原始内容。
例如,您可以
localStorage.setItem(JSON.stringify(!this.state.addFavorite)) //ie "true" || "false"
并将其恢复为
getInitialState = () => {
let fav = localStorage.getItem('AddFavorite');
let addFavorite = JSON.parse(fav || "true");
this.setState({ addFavorite });
}
PS:如果不破坏功能,建议您在componentWillUnmount
中设置localStorage。设置本地存储和JSON序列化会影响性能。