javascript - 刷新后 React-Redux 状态丢失

标签 javascript reactjs redux

我真的是 React 和 Redux 的新手,我一直在学习 Stephen Grider 的 Advanced React and Redux 类(class),并且我正在做身份验证的客户端。我已经在我的本地存储中保存了一个 token ,在我刷新页面之前一切似乎都运行良好。当我登录/注册时,导航会更改为显示注销按钮,但如果我手动刷新页面,导航会变回显示登录/注册按钮。

我对此很陌生,不知道应该将什么作为代码片段包含在内。我将保留 reducer 和 actions/index.js。还有 this喜欢我的 git 仓库。

Action /index.js

import axios from 'axios';
import { browserHistory } from 'react-router';
import { push } from 'react-router-redux';
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR } from './types';

const API_URL = 'http://localhost:3000';

export function signinUser({ username, password }) {
  return function(dispatch) {
    // Submit username/password to the server
    axios
      .post(`${API_URL}/signin`, { username, password })
      .then(response => {
        // If request is good...
        // - Update state o indicate user is authenticated
        dispatch({ type: AUTH_USER });
        // - Save the JWT token to local storage
        localStorage.setItem('token', response.data.token);
        // - Redirect to the route '/feature'
        browserHistory.push('/feature');
      })
      .catch(() => {
        // If request is bad...
        // -Show an error to the user
        dispatch(authError('Bad login info'));
      });
  };
}

export function signupUser({ username, email, password }) {
  return function(dispatch) {
    axios
      .post(`${API_URL}/signup`, { username, email, password })
      .then(response => {
        dispatch({ type: AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/feature');
      })
      .catch(response => {
        // TODO
        console.log(response);
        dispatch(authError('There was an error'));
      });
  };
}

export function authError(error) {
  return {
    type: AUTH_ERROR,
    payload: error
  };
}

export function signoutUser() {
  localStorage.removeItem('token');
  return { type: UNAUTH_USER };
}

reducer/auth_reducer.js

import { AUTH_USER, UNAUTH_USER, AUTH_ERROR } from '../actions/types';
export default function(state = {}, action) {
  switch (action.type) {
    case AUTH_USER:
      return { ...state, error: '', authenticated: true };
    case UNAUTH_USER:
      return { ...state, authenticated: false };
    case AUTH_ERROR:
      return { ...state, error: action.payload };
  }

  return state;
}

提前致谢,如果您需要任何额外的代码片段,请告诉我。

最佳答案

do not reinvent the wheel

要在页面刷新后存储 redux 状态,您可以使用

https://www.npmjs.com/package/redux-persist

它易于实现且健壮。

关于javascript - 刷新后 React-Redux 状态丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46673204/

相关文章:

Javascript解析已按顺序履行的 promise 数组中的第一个元素

javascript - 主页中的隐藏内部链接(可以通过 onclick 事件显示)用于 SEO?

javascript - 'year()' 和 'format(' YYYY')' 有什么区别?

javascript - Require 没有出现在我的代码中,但是 webpack 一直抛出错误 "require is not defined."

reactjs - 如何解决: Type error: 'Draggable' cannot be used as a JSX component ?(react-draggable)

javascript - react Hook : Parent component not updating when dispatch is called in a child component

javascript - react-redux Provider 在 IE 10/11 中给出错误 “onlyChild must be passed a children with exactly one child”

javascript - 如何通过调用函数呈现弹出窗口?

javascript - 在 Chrome 内容脚本和弹出脚本之间共享一个 redux store

reactjs - Redux:如何进行后端持久化的意见/示例?