【发布时间】:2021-11-03 14:39:10
【问题描述】:
我正在尝试在 React 中保持页面刷新后的状态:
这是我的代码:
class App extends React.Component{
constructor(props){
super(props);
this.state = JSON.parse(localStorage.getItem("app_state")) ? JSON.parse(localStorage.getItem("app_state")) : {
account: {
email: "",
password: ""
},
token: "",
authenticated: false
};
}
componentDidUpdate(prevProps, prevState){
if(this.state.token !== prevState.token){ //set a new state if token changes
localStorage.setItem("app_state", this.state);
}
}
logInStatus = () =>{
if(!this.state.authenticated) {
return (
<form onSubmit={this.handleSubmit}>
<label>Email Address</label>
<input type="text" value={this.state.passAccount.email} onChange={this.handleChange} name="email"/>
<label>Password</label>
<input type="password" value={this.state.passAccount.password} onChange={this.handleChange} name="password" />
<br/>
<Button type="submit" onClick={() => {
this.someFunction(String(this.state.passAccount.email));
}}>
Sign In</Button>
</Form>
);
}else{
return(<Redirect to="/some/endpoint" />);
}
}
}
export default App;
这是我正在做的以防止页面刷新时丢失状态:
在 componentDidUpdate 方法中,我正在检查令牌,如果不是 fount/与状态令牌不同,我将其保存在本地存储中。
在构造函数的状态中,我从本地存储中获取状态。
但是,我在页面刷新时收到以下错误:
我的代码有什么问题,需要修复什么?
【问题讨论】:
标签: javascript reactjs react-router react-hooks local-storage