javascript - 在 React 中持久化内存
问题描述
这是我的代码,我通过道具将身份验证状态和令牌传递给其他组件:问题是当我刷新页面时,它会将我重定向到主页。
这是我的代码:
class App extends React.Component{
constructor(props){
super(props);
this.state = {
account: {
email: "",
password: ""
},
token: "",
auth: false
};
}
confirm = async (email) => {
let result;
let stateAccount;
let authToken;
let myCookie;
let storedCookie;
try {
result = await axios.post(`http://localhost:5000/abc/dosomething`, {email},{withCredentials: true});
stateAccount = this.state.account
stateAccount.email = email;
this.setState({stateAccount});
console.log(result);
if (this.state.account.email === result.data.Email && this.state.account.password === result.data.OTPCode) {
authToken = result.headers.accesstoken;
this.setState({token: authToken});
myCookie = this.addCookies();
myCookie = myCookie.split('=');
storedCookie = myCookie[1].trim();
} else {
console.log(`Invalid Login!`);
}
let history = this.props.history;
if(this.state.token === storedCookie){
console.log("Successful Login!");
console.log(`found cookie: ${storedCookie}`);
this.setState({auth: true});
history.push({pathname: "/some-endpoint/abc", state: {stateAccount}});
}else{
this.setState({errorMessage: "Invalid Login!"});
}
}catch(error){ //set this to Permission Denied in production
console.log(`${error.data}`});
}
}
notLoggedInhomePage = () =>{
if(!this.state.auth) {
return (
<form onSubmit={this.handleSubmit}>
<label>Email Address</Form.Label>
<input type="text" value={this.state.account.email} onChange={this.handleChange} name="email"/>
<label>Password</Form.Label>
<input type="password" value={this.state.account.password} onChange={this.handleChange} placeholder="Enter One Time Password" name="password"/>
<button type="submit" onClick={() => this.someFunction(String(this.state.account.email))}>Do Something</button>
<button type="submit" onClick={() => this.someOtherFunction()}>Do something else</button>
</form>
);
}else{
return(<Redirect to="/logged-in-page/signed-in" />);
}
}
render(){
return(
<Router>
{this.notLoggedInhomePage()}
<Switch>
<Route path="/list" exact component={AComponent} auth={this.state.auth} account={this.state.account} token={this.state.token} />
</Switch>
</Router>
);
}
我知道状态是一个临时内存,但我想做的是,当我刷新页面时,我希望用户停留在刷新之前他们所在的页面上。然而,发生的情况是它们被重定向回主页(即登录屏幕),因为 this.state.auth 将等于 false,如上面在 notLoggedInhomePage 中所见。
解决上述问题的最佳解决方案是什么?
解决方案
你可以利用localStorage
app_state
更改令牌时将状态设置为存储。- 检查
app_state
挂载上是否存在或使用新状态。
像这样的东西:
class App extends React.Component {
constructor(props) {
super(props);
this.state = localStorage.getItem("app_state") ?? {
account: {
email: "",
password: ""
},
token: "",
auth: false
};
}
componentDidUpdate(prevProps, prevState) {
if (this.state.token !== prevState.token) { // Set a new state if token change
localStorage.setItem("app_state", this.state);
}
}
...the rest of your component
推荐阅读
- android - 更改按钮颜色会导致按钮变大
- apache-spark - 如何使用 YARN 客户端模式在 Jupyter 中以交互方式运行 Pyspark?
- sorting - 将 jinja 列表中的值四舍五入
- android - 在从活动移动到片段时实现抽象方法
- c# - Throttling connections on 429 errors in WebClient mechanism, best practice?
- mysql - mysql 只有在前 12 条最新记录中才选择用户
- r - local image in shiny app without img(src())?
- django-rest-auth - 使用 rest-auth 注册时无法发送确认电子邮件
- ios - 如何在 Watch OS 中使用 webview 或类似控件?
- java - 计算斐波那契数列中终止条件的执行情况