刷新页面后,我被注销了?为什么?



我使用Redux与ReactJS。我也在使用设计jwt进行验证。在刷新页面时,我的状态改变了,loggedIn变成了"false"。我也得到400坏的请求错误后,通过获取发布数据。我可以很好地登录并被重定向。

我的用户reducer:

import {
SIGNUP_USER, 
LOGIN_USER,
LOGOUT_USER,
STORE_TOKEN
} from '../actions/types'
const INITIAL_STATE = {
loggedIn: false,
currentUser: {}
} 
export default (state = INITIAL_STATE, action) => {
switch(action.type){
case SIGNUP_USER:
return {
...state, 
loggedIn: true,
currentUser: action.payload
}
case LOGIN_USER:
return {
...state, 
loggedIn: true,
currentUser: action.payload
}
case LOGOUT_USER:
return { 
...state, 
user: state.users.filter(user => user.id !== action.payload.id),
loggedIn: false
}
case STORE_TOKEN:
return {
token: action.payload.token,
}
default:
return state
}
}

我的行动:

export function loginUser(data){
return (dispatch) => {
fetch("http://localhost:3000/login", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user: {
...data
}
})
})
.then(resp => {
//debugger
if (resp.ok) {
resp.json().then(json => {
localStorage.setItem('token', json.token)
dispatch({ type: LOGIN_USER, payload: json })
})

} 
})
}
}

我的登录组件:

import React from 'react'
import TextField from '@material-ui/core/TextField'
import Button from '@material-ui/core/Button'
import { loginUser } from '../actions/index'
import { connect } from 'react-redux'
class Login extends React.Component {
state = {
email: '',
password: ''
}

handleSubmit = (e) =>{
e.preventDefault()
let credentials  = this.state
this.props.loginUser(credentials)
this.props.history.push('/bookmarks')

}

handleChange = (e) => {
this.setState({[e.target.name]: e.target.value})
}

render() {
const { email, password } = this.state
return (
<div className="login-form">
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
<div>
<TextField type="text" name="email" placeholder="Email" onChange={this.handleChange} value={email} />
</div>
<div>
<TextField type="password" name="password" placeholder="Password" onChange={this.handleChange} value={password}/>
</div><br></br>
<Button type="submit" value="Login">Login</Button>
</form>
</div>
)
}
} 

const mapDispatch = (dispatch) => {
return {
loginUser: (credentials) => dispatch(loginUser(credentials))

}
}

export default connect(null, mapDispatch)(Login)

我使用了设计- jwt进行身份验证。

您已注销,因为您存储凭据的唯一位置是redux存储区,该存储区(本质上)是一个变量。

刷新页面时,将存储重新初始化为默认状态。

您没有将凭据存储在它们会持久存在的任何地方,例如本地存储或cookie。

相关内容

  • 没有找到相关文章

最新更新