【发布时间】:2019-10-10 03:57:24
【问题描述】:
import React, { Component } from "react";
import axios from 'axios';
class login extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ [event.target.id]: event.target.value });
}
handleSubmit(event) {
axios.post('http://localhost:8080/validateAccount', {
"username": this.state.username,
"password": this.state.password
})
.then(function (response) {
console.log(response.data)
if(response === 'success') {
localStorage.setItem('loggedin', 'true');
console.log(response.data);
}
})
.catch(function (error) {
console.log(error);
});
event.preventDefault();
}
checkStorage() {
console.log(localStorage.getItem('loggedin'))
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input id="username" type="text" value={this.state.username} onChange={this.handleChange} /> <br></br>
</label>
<label>
Password
<input id="password" type="password" value={this.state.password} onChange={this.handleChange} /> <br></br>
</label>
<input type="submit" value="Submit" />
<div id="typehere"></div>
</form>
<button onClick={this.checkStorage}>test</button>
</div>
);
}
}
export default login;
我目前正在练习 react js,我正在尝试模仿 PHP $_SESSION['some-value'] 函数,它基本上保存会话值,直到您使用 session_destroy() 终止它(注销)。
我认为 localStorage 正是如此,但它没有保存它?上面是一个有效的登录表单,如果我输入了一个有效的用户名密码,那么它会到达 console.log("success") 并且 "loggedin" 在本地存储中设置为 true。现在,如果我使用“test”按钮,它将从本地存储中获取“loggin”并且应该返回 true,但它会返回 null。为什么?
我使用有效帐户登录并获得“成功”,然后立即进行快速测试并返回“null”。无论如何要得到我想要的?
【问题讨论】:
标签: reactjs