javascript - ReactJS:如何使用 localStorage 更新属性状态?
问题描述
我有一个具有以下初始状态的组件:
constructor(props) {
super(props)
this.state = {
currentId: 0,
pause: true,
count: 0,
storiesDone: 0
}
this.defaultInterval = 4000
this.width = props.width || 360
this.height = props.height || 640
}
我必须从开始currentId = 0
然后更新组件的状态,即使在页面刷新之后也是如此。
我想currentId = 1
在保持1
.
当我尝试currentId = localStorage.getItem('currentId')
在上面的代码中替换时,出现属性无法更改的错误。
var currentId = this.state.currentId;
localStorage.setItem( 'currentId', 1);
console.log(currentId);
localStorage.getItem('currentId');
我也试过:
_this.setState((state) => {
return {currentId: localStorage.getItem('currentId')};
});
解决方案
持久化的值类型localStorage
必须是字符串。
考虑修改与之交互的代码,localStorage
以便在将状态值currentId
传递给之前先将其转换为字符串localStorage.setItem()
。
另请注意,字符串值是在存在键时返回的localStorage.getItem()
,这意味着您应该解析返回的值以获取currentId
为数字。
类似这样的东西应该可以工作:
const saveCurrentId = () => {
const { currentId } = this.state;
/* Format string from value of currentId and persist */
localStorage.setItem( 'currentId', `${ currentId }`);
}
const loadCurrentId = (fallbackValue) => {
/* Load currentId value from localStorage and parse to integer */
const currentId = Number.parseInt(localStorage.getItem('currentId'));
/* Return currentId if valid, otherwise return fallback value */
return Number.isNaN(currentId) ? fallbackValue : currentId;
}
使用上面的代码,您可以更新组件构造函数以自动加载和应用持久化currentId
,如下所示:
constructor(props) {
super(props)
this.state = {
/* Use 0 as fallback if no persisted value present */
currentId: this.loadCurrentId( 0 ),
pause: true,
count: 0,
storiesDone: 0
}
this.defaultInterval = 4000
this.width = props.width || 360
this.height = props.height || 640
}
推荐阅读
- c# - WIX 图标无法正常工作
- sql - 需要查询以选择带有作者姓名的特定评论
- url-parameters - 如何在 opencart 3.x 中向 url 添加优惠券代码和产品 ID?
- xcode - 找不到具有以下名称的广告网络适配器:com.google.DummyAdapter
- c# - 将指数形式的数字转换为十进制
- android - FirebaseRecyclerAdapter 触发两次
- c++ - char *a[] ={"yes","no"} 是否需要 malloc?
- javascript - 当我们单击动态创建的编辑图标时,如何更改输入字段中的值?
- python - Python:将文件中的字符串与字符串文字连接起来
- amazon-web-services - AWS Amplify 在 API 请求中使用访客凭证,而不是经过身份验证的凭证