我得到一个状态值,即登录用户名,然后在我的页面上打印登录用户名。但是当我刷新页面时,状态值丢失了。
我正在使用 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({}));
};
Run Code Online (Sandbox Code Playgroud)
这是我的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
在 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>
);
Run Code Online (Sandbox Code Playgroud)
我正在获取登录用户名的状态。但是当我刷新页面时,登录用户名的状态值丢失了。还有一件事,我在我的 react 应用程序的所有页面中都包含了 Header.js 文件。
如果我刷新页面,如何保存我的登录用户状态值免受任何损失?
当我刷新页面时,状态值丢失
这就是 React 和 Redux 状态的工作方式。它们仅在页面加载时存储在内存中。看起来您已经将令牌存储在本地存储中,这是更永久地存储数据的正确方法。问题是当您的页面加载时,您永远不会从本地存储中取回值。您应该检查本地存储中是否存在令牌。如果是这样,那么只需获取它。如果没有,则重定向到登录屏幕。
React 应用程序的两种常见存储是组件内部状态和redux. 卸载该组件时无法访问定义为状态的参数。因此,当您从页面路由或刷新时,您会丢失状态。但是,如果您在redux商店中设置参数,则可以在整个应用程序中访问该参数。在这种情况下,如果您刷新页面,您会redux因为从一个页面路由到另一个页面而丢失您的商店,您仍然可以访问您的商店。所以如果你想在你的商店中有一个参数:
首先在redux商店中设置,然后将其保存在localStorage浏览器中。保存、获取和删除参数localStorage可以参考这个链接:https : //developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
但是正确的方法是使用redux-persist库并将参数放入其white-list. 你可以在这里阅读更多相关信息:https :
//github.com/rt2zz/redux-persist
我希望它会有所帮助。如果是,请投票给我:)
| 归档时间: |
|
| 查看次数: |
5269 次 |
| 最近记录: |