我使用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上 –