我得到一个状态值,即登录用户名,然后在我的页面上打印登录用户名。但是当我刷新页面时,状态值就会丢失。
我正在使用 redux 创建状态值。
这是我的action.js -
// Login - get user token
export const loginUser = userData => dispatch => {
axios
.post("http://localhost:5000/login", userData)
.then(res => {
// Save to localStorage
// Set token to localStorage
const { token } = res.data;
localStorage.setItem("usertoken", token);
// Set token to Auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
})
.catch(err => {
return err;
}
);
};
// Set logged in user
export const setCurrentUser = decoded => {
return {
type: SET_CURRENT_USER,
payload: decoded
};
};
// User loading
export const setUserLoading = () => {
return {
type: USER_LOADING
};
};
// Log user out
export const logoutUser = () => dispatch => {
// Remove token from local storage
localStorage.removeItem("usertoken");
// Remove auth header for future requests
setAuthToken(false);
// Set current user to empty object {} which will set isAuthenticated to false
dispatch(setCurrentUser({}));
};
这是我的reducer.js -
import {
SET_CURRENT_USER,
USER_LOADING
} from "../Actions/actions";
const isEmpty = require("is-empty");
const initialState = {
isAuthenticated: false,
user: {},
loading: false
};
export default function (state = initialState, action) {
switch (action.type) {
case SET_CURRENT_USER:
return {
...state,
isAuthenticated: !isEmpty(action.payload),
user: action.payload
};
case USER_LOADING:
return {
...state,
loading: true
};
default:
return state;
}
}
在 header.js 中我正在打印登录的用户名。
const userLink = () => (
<div className="" style={{ display: "inline-flex" }}>
<li class="nav-item">
<Link className="nav-link" to="/">
{user.name}
</Link>
</li>
<li class="nav-item">
<a href="" onClick={this.logOut.bind(this)} className="nav-link">
Logout
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/">
AboutUs
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/">
ContactUs
</a>
</li>
</div>
);
我正在获取登录用户名状态。但是当我刷新页面时,已登录用户名的状态值丢失了。另一件事是我将 Header.js 文件包含在我的 React 应用程序的所有页面中。
如果刷新页面,如何保存已登录用户的状态值以避免任何损失?
最佳答案
when I refresh my page then the state value is lost
这就是 React 和 Redux 状态的工作原理。它们仅在页面加载时存储在内存中。看起来您已经将 token 存储在本地存储中,这是更永久地存储数据的正确方法。问题是,当页面加载时,您永远不会从本地存储中取回该值。您应该检查本地存储中是否存在该 token 。如果是这样,那么只需获取它即可。如果没有,则重定向到登录屏幕。
关于reactjs - 刷新时状态值在react.js中丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57765453/