使用LocalStorage和React? [英] Using LocalStorage with React?

查看:387
本文介绍了使用LocalStorage和React?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我目前所遇到的情况,似乎ReactJS不会更新localStorage的状态。我的代码如下。

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>
);}


}
});

简单的申请。如果localstorage的状态为off或empty,则使用ON按钮渲染视图。如果启用了localstorage,则使用OFF按钮渲染视图。

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.

我希望能够根据localStorage的状态设置此渲染。我尝试使用基本布尔值做同样的事情,它按预期工作。但是,使用localStorage时,某些内容似乎不起作用。

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.

编辑:解释,按钮并且视图不会按预期运行。当指示灯熄灭且存储中没有任何内容时,该按钮会将ON添加到localStorage,但不会更改视图。如果我刷新页面,页面呈现为ON,当我点击它时,按钮的工作方式是关闭它。但它只能工作一次,这让我相信OFF开关可能有问题。

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.

推荐答案

.setItem()本地存储函数返回未定义。您需要执行本地存储更新,然后返回新的状态对象:

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'}); 
},

这篇关于使用LocalStorage和React?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆