From what I am experiencing so far, it doesn't seem like ReactJS updates with the state of localStorage. My code below.
var Frr = React.createClass({
getInitialState: function(){
return { lights: localStorage.getItem('state')}
},
switchoff: function(){
this.setState({lights: localStorage.setItem('state', 'off')});
},
switchon:function(){
this.setState({lights: localStorage.setItem('state', 'on')});
},
render:function(){
if (this.state.lights === 'on'){ return (
<div>
<p>The lights are ON</p>
<input type="submit" value="Switch" onClick={this.switchoff}/>
</div>
);}
if ( (this.state.lights === 'off')|| (!this.state.lights) ){ return (
<div>
<p>The lights are OFF</p>
<input type="submit" value="Switch" onClick={this.switchon}/>
</div>
);}
}
});
Simple application. If the state of localstorage is off or empty, then render the view with the ON button. If localstorage is on, then render the view with the OFF button.
I want to be able to set this render based on the state of localStorage. I have tried doing the same thing using basic booleans, and it works as expected. However, when using localStorage, something doesn't appear to work.
I wouldn't be surprised if my logic is simply off.
EDIT: To explain, the button and the view don't act as they should. When the lights are off and there is nothing in Storage, the button adds ON to localStorage, but does not change the view. If I refresh the page, the page renders ON, and when I click on it the button works by turning it OFF. But it only works once, which leads me to believe there may be a problem with the OFF switch.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…