【问题标题】:piece of redux state changes to null when I try to print it in a component当我尝试在组件中打印时,redux 状态变为 null
【发布时间】:2020-12-31 14:01:17
【问题描述】:

我正在尝试在仪表板组件上显示用户信息,只需简单:

const mapStateToProps = state => ({
  user: state.authReducer.user
})

当我登录或注册时,会调用相应的操作以及 USER_LOADED 操作;所有用户信息都显示在 redux-logger 中,用户对象显示“name”、“id”和其他信息。但是,当我尝试使用

发布用户名时
const Dashboard = ({ user, isAuthenticated }) => {
  return (
    <div>
      {user.name}
    </div>
  )
}

一切都变为空,包括 isAuthenticated 值(在成功登录后最初设置为 true。)我可以在用户对象上使用 JSON.stringify,它可以很好地显示它们的值,但是如果我尝试将 JSON.stringify 与 user.name 一起使用,我得到下面显示的相同错误,其中值变为空。 为什么我会尝试列出用户 redux 状态导致它的值变为空? 我用的是redux-persist(不知道跟这个有没有关系)

Dashboard.js(组件):

import React from 'react'
import { connect } from 'react-redux';

const Dashboard = ({ user, isAuthenticated, token }) => {
  return (
    <div>
     {user.name}
    </div>
  )
}

const mapStateToProps = state => ({
  user: state.authReducer.user
})
export default connect(mapStateToProps)(Dashboard);

authReducer.js:

import {
  REGISTER_SUCCESS,
  REGISTER_FAIL,
  USER_LOADED,
  AUTH_ERROR,
  LOGIN_FAIL,
  LOGIN_SUCCESS,
  LOGOUT,
  ACCOUNT_DELETED
} from '../../actions/types';

const initialState = {
  token: localStorage.getItem('token'),
  isAuthenticated: null,
  loading: true,
  user: null
}

const authReducer = (state = initialState, action) => {
  const { type, payload } = action;

  switch (type) {
    case USER_LOADED:
      return {
        ...state,
        isAuthenticated: true,
        loading: false,
        user: payload
      }
    case REGISTER_SUCCESS:
    case LOGIN_SUCCESS:
      localStorage.setItem('token', payload.token);
      return {
        ...state,
        ...payload,
        isAuthenticated: true,
        loading: false
      }

    case REGISTER_FAIL:
    case AUTH_ERROR:
    case LOGIN_FAIL:
    case LOGOUT:
    case ACCOUNT_DELETED:
      localStorage.removeItem('token');
      return {
        ...state,
        token: null,
        isAuthenticated: false,
        loading: false
      }

    default:
      return state;
  }
}

export default authReducer;

身份验证(操作):

import axios from 'axios';
import { setAlert } from './alert';

import {
  REGISTER_SUCCESS,
  REGISTER_FAIL,
  USER_LOADED,
  AUTH_ERROR,
  LOGIN_FAIL,
  LOGIN_SUCCESS,
  LOGOUT,
  CLEAR_PROFILE
} from './types';

import setAuthToken from '../utils/setAuthToken';

//LOAD USER
export const loadUser = () => async dispatch => {
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  }

  try {
    const res = await axios.get('/api/auth');

    dispatch({
      type: USER_LOADED,
      payload: res.data
    })
  } catch (err) {
    dispatch({
      type: AUTH_ERROR
    })
  }
}

//Register user
export const register = ({ name, email, password }) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  }

  const body = JSON.stringify({ name, email, password });

  try {
    const res = await axios.post('/api/users', body, config);

    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data
    });

    dispatch(loadUser());

  } catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: REGISTER_FAIL
    })
  }
}

//Login user
export const login = (email, password) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json',
    }
  }

  const body = JSON.stringify({ email, password });

  try {
    const res = await axios.post('/api/auth', body, config);

    dispatch({
      type: LOGIN_SUCCESS,
      payload: res.data
    });

    dispatch(loadUser());
  } catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: LOGIN_FAIL
    })
  }
}

//Logout clear profile
export const logout = () => dispatch => {
  dispatch({
    type: CLEAR_PROFILE
  });
  dispatch({
    type: LOGOUT
  });

}

auth.js(验证用户/获取令牌的路由):

const express = require('express');
const router = express.Router();
const auth = require('../../middleware/auth');
const User = require('../../models/User');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const config = require('config');
const { check, validationResult } = require('express-validator');

//@route GET api/auth
//@desc Test route
//@access Public
router.get('/', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.id).select('-password');
    res.json(user);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

//@route POST api/auth
//@desc Authenticate user and get token
//@access Public
router.post('/', [
  check('email', 'Please include a valid email').isEmail(),
  check('password', 'Password is required').exists()
], async (req, res) => {
  const errors = validationResult(req);

  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() })
  }

  const { email, password } = req.body;

  try {
    let user = await User.findOne({ email })

    if (!user) {
      return res.status(400).json({ errors: [{ msg: 'Invalid credentials' }] })
    }


    const isMatch = await bcrypt.compare(password, user.password);

    if (!isMatch) {
      return res.status(400).json({ errors: [{ msg: 'Invalid credentials' }] });
    }

    const payload = {
      user: {
        id: user.id
      }
    }
    jwt.sign(payload,
      config.get('jwtSecret'),
      { expiresIn: 360000 },
      (err, token) => {
        if (err) throw error;
        res.json({ token })
      });

  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }


});

module.exports = router;

主页还原值:

我点击仪表板,商店似乎已重置: 尝试显示用户对象的任何部分时出现此错误:

【问题讨论】:

  • 请分享一大堆代码。 @connect、reducer 等等。很难从碎片中找出问题。
  • @AlexanderAlexandrov 我已经添加了适当的减速器、组件、动作文件和路由文件。如果我遗漏了什么,请告诉我,感谢您的纠正。
  • intialState 中的用户为空。因此,初始渲染因 NPE 而失败。 Dashboard 组件内部可能需要一些保护?
  • @AlexanderAlexandrov 就像商店在导航到仪表板(受保护的路线)时重置一样。我包含两张显示主页商店(具有用户对象)和导航到仪表板后的图片(它重置了商店,看起来像。)它可能是 redux 坚持重新水化到初始状态吗?
  • 更新,当我登录时,它会正确转发到显示用户名的仪表板。但是,如果我刷新页面,我的令牌仍然处于 Redux 状态,但是 user 和 isAuthenticated 设置为 null,同时调用了 PERSIST 和 REHYDRATE 操作。 Auth reducer 包含在持久存储中,所以我不确定它为什么要重置。其他值通过刷新保持,所以这很奇怪。

标签: reactjs redux


【解决方案1】:

已回答我的根 reducer 中的 persistConfig 对象的白名单中没有我的 auth reducer。数据没有持久化,因为它没有被列为持久化facepalm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    相关资源
    最近更新 更多