我使用CodePen作为ReactJS项目。 我需要设置localStorage
为国家的一部分,那就是:如何正确设置ReactJS中的localStorage?
this.state={
Things:{
element:"value",
element2: "value"
},
activated:-1
}
因为我需要设置只Things
我决定设置localStorage
在组件的生命周期:componentDidUpdate()
componentDidUpdate(prevProps,prevState){
localStorage.setItem("myThings",JSON.stringify(this.state.Things));
}
这里如果我拨打console.log(localStorage.getItem("myThings"))
我没有得到任何储值。
对于localStorage
检查部分,我在构造函数中实现了一个解决方案,因为我在React文档中看到,应该更喜欢构造函数到componentWillMount()
方法(尽管我也尝试了后者)。
constructor(props){
super(props);
if (localStorage.getItem("myThings")!==null){
this.state={
Things:JSON.parse(localStorage.getItem("myThings")),
activated:-1
}
}
...
错字仅在stackoverflow上 –