Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - Using LocalStorage with React?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The .setItem() local storage function returns undefined. You need to perform the local storage update and then return the new state object:

switchoff: function(){
    localStorage.setItem('state', 'off');
    this.setState({lights: 'off'}); 
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...