Javascript ReactJS:如何使用localStorage更新属性的状态?
我有一个具有以下初始状态的文件:Javascript ReactJS:如何使用localStorage更新属性的状态?,javascript,reactjs,local-storage,Javascript,Reactjs,Local Storage,我有一个具有以下初始状态的文件: 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.
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
开始,然后更新组件的状态,即使在页面刷新之后也是如此
我想在保持值1
后恢复currentId=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
}
使用componentDidMount。请参阅下面的代码。我添加了检查localStorage.currentId是否有值。如果有,请检查localStorage.currentId中的值是否与状态的currentId匹配,如果不匹配,则将状态更新为localStorage中的值
state = {
currentId: 0,
pause: true,
count: 0,
storiesDone: 0
}
componentDidMount() {
//Assign localStorage.get("currentId") to a variable
const localCurrentId = localStorage.get("currentId");
//Check if localCurrentId is not null or undefined
if (localCurrentId) {
this.setState(prevState => ({
//Update state's currentId if the current value didn't match with localCurrentId
currentId: prevState.currentId !== localCurrentId ? localCurrentId : prevState.currentId
}));
}
}
只需在构造函数中设置默认状态定义以使用localstorage值我正在尝试此方法,但它不会从控制台读取,我只看到“null”。尝试
localStorage.getItem('currentId')
时。非常感谢您的更新。我会试试最新的edit@JonasKgomo不客气,如果您有任何问题,请告诉我解决方案说,saveCurrentId
已声明但从未使用,localStorage
仍返回null。但是,第二个变量loadcurrentId
很适合构造函数。@JonasKgomo很高兴使用loadcurrentId()
工作-如何调用/使用saveCurrentId()
?类似的东西应该在onClick prop中起作用:onClick={()=>this.saveCurrentId()}
我希望它在状态更改时启动(自动),我的意思是当状态从0
更改为1
时,这是我的错误,我没有调用它。