出于某种原因,我无法在 redux 中查看我的状态

时间:2021-05-19 10:02:33

标签: reactjs redux react-redux

enter image description hereenter image description here我正在学习 redux,我正在尝试使用 useSelector 钩子从 state 中提取值,但我真的不知道为什么我看不到我的错误和从 state 加载属性这是在用户 obj 里面。我也在商店中使用初始状态,当我尝试控制台日志 userInfo、error 和 loading 时,我只能看到 userInfo 而不是加载和错误。商店中的初始状态是否会导致此问题?请帮帮我..谢谢

我的代码

login.js

import React, {useState, useEffect} from 'react';
import {useSelector, useDispatch} from 'react-redux';
import {loginUser, logoutUser} from '../../actions/userAction';
import {alert} from '../../actions/alertAction';

const Login = (props) => {
    const dispatch = useDispatch();
    const user= useSelector(state => state.user)
    const alertMsg = useSelector(state => state.alert)
    **console.log(user)**
    **const {userInfo, loading, error} = user**
     **console.log(userInfo, loading, error)**


return ("<h1>welcome to login page")
}

userAction.js 文件

 import {USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS,USER_LOGIN_ERROR, USER_REGISTER_REQUEST, USER_REGISTER_SUCCESS, USER_LOGOUT_SUCCESS} from '../types';
import axios from 'axios';

export const loginUser = (email, password) => async(dispatch) => {

    try {
        console.log('login user')
        dispatch({
            type: USER_LOGIN_REQUEST,
        });
    
        const config = {
            headers: {
                "Content-Type": "application/json",
            },
        };
        const {data} = await axios.post(
            "/user/login",
            { email, password },
            config
        );
        dispatch({
            type: USER_LOGIN_SUCCESS,
            payload: data,
        });
            localStorage.setItem("userInfo", JSON.stringify(data));
    }catch(error) {
        console.log(error)
        dispatch({
            type: USER_LOGIN_ERROR,
            payload: error.response.data.msg
        })
    }
    

}

userReducer.js 文件

     import {USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_REGISTER_REQUEST,USER_LOGIN_ERROR, USER_REGISTER_SUCCESS, USER_LOGOUT_SUCCESS} from '../types';


export default (state = {}, action) => {
    switch (action.type) {
      case USER_LOGIN_REQUEST:
        return {
          ...state,
          user: {loading: true}
        };
      case USER_LOGIN_SUCCESS:
        return {
          ...state,
          user: {
            userInfo: action.payload, loading: false
          }
        }
      case USER_LOGIN_ERROR:
              return {
                ...state,
                user: {
                  loading: false, error: action.payload
                }
              }
      case USER_LOGOUT_SUCCESS:
          return {
            ...state
          };
      default: 
          return state
      }
  }

index.js 文件

import {combineReducers} from 'redux';
import cartReducer from './cartReducer';
import userReducer from './userReducer';

export default combineReducers({
    cart: cartReducer,
    user: userReducer
})

store.js 文件

import  { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index.js';

const cartItemsFromStorage = localStorage.getItem('cartItems') ? JSON.parse(localStorage.getItem('cartItems')) : []
const userInfoFromStorage = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : null
const initialState = {
    **cart: {
        cartItems: cartItemsFromStorage
    },
    user: {
        userInfo: userInfoFromStorage
    }**
};

const middleware = [thunk];

const store = createStore(rootReducer, initialState, composeWithDevTools(applyMiddleware(...middleware)));

export default store;

enter image description here

1 个答案:

答案 0 :(得分:0)

问题在于您如何在 redux 中存储数据。

case USER_LOGIN_REQUEST:
        return {
            ...state,
          loading: true,  // Here you are storing loading in redux state directly
          error: null  // same as loading
        };

要解决这个问题,您需要像下面这样存储:-

case USER_LOGIN_REQUEST:
        return {
            ...state,
          user: { ...state.user, loading: true, error: null}
        };

您还需要针对您尝试在 loading 中存储 erroruser 的所有情况更改此设置

相关问题