尽管登录工作正常,但 React Redux 没有更新状态

时间:2021-03-01 22:24:45

标签: reactjs redux react-redux

所以我的减速器没有更新我的应用程序的状态。 user 中的初始状态显示,没有进行任何更改。 uiReducer 的初始状态根本没有出现。强调文字我可以正常登录并收到令牌,所以我认为是getUserData的问题。我不知道为什么 ui 初始状态不起作用。这是我第一次尝试使用 react redux,所以我可能在某个地方犯了一个愚蠢的错误。任何帮助表示赞赏!

编辑:没有更改代码,我只是重新启动了我的应用程序,现在两个初始状态都在加载,但用户仍然没有填充数据。

登录

import React, { Component } from 'react';
import PropTypes from 'prop-types'

// redux
import {connect} from 'react-redux'
import {loginUser} from '../redux/actions/userActions'

class login extends Component {
    constructor(props) {
        super(props);

        this.state = {
            email: '',
            password: '',
            errors: [],
        };
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.UI.errors) {
            this.setState({
                errors: nextProps.UI.errors
            });
        }
    }

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value
        });
    };

    handleSubmit = (event) => {
        event.preventDefault();
        const userData = {
            email: this.state.email,
            password: this.state.password
        };
        this.props.loginUser(userData, this.props.history)
    };

    render() {
        const { classes, UI: {loading} } = this.props;
        const { errors } = this.state;
        return (
            ..............
        );
    }
}
login.propTypes = {
    classes: PropTypes.object.isRequired,
    loginUser: PropTypes.func.isRequired,
    user: PropTypes.object.isRequired,
    UI:PropTypes.object.isRequired

}

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

const mapActionsToProps = {
    loginUser
}

export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(login));

用户操作

import axios from 'axios';

export const loginUser = (userData, history) => (dispatch) => {
    dispatch({ type: 'LOADING_UI' });
    axios
        .post('/login', userData)
        .then((res) => {
            setAuthorizationHeader(res.data.token);
            dispatch(getUserData())
            dispatch({type: 'CLEAR_ERRORS'})
            history.push('/');
        })
        .catch((error) => {             
            dispatch({
                type: 'SET_ERRORS',
                payload: error.response.data
            });
        });

}

export const getUserData = ()=> (dispatch) => {
    axios
        .get('/user')
        .then(res => {
           dispatch({
               type: 'SET_USER',
               payload: res.data
           })
        })

}

const setAuthorizationHeader = (token) => {
    const FBIdToken = `Bearer ${token}`;
    localStorage.setItem('FBIdToken', FBIdToken);
    axios.defaults.headers.common['Authorization'] = FBIdToken;
};

userReducer

const initialState = {
    authenticated: false,
    credentials: {},
    approves: []
}

export default function(state = initialState, action){
    switch(action.type){
        case 'SET_AUTHENTICATED':
            return{
                ...state,
                authenticated: true
            }
        case 'SET_UNAUTHENTICATED':
            return initialState
        case 'SET_USER':
            return{
                authenticated: true,
                loading: false,
                ...action.payload
            }
        default:
            return state
    }
}

uiReducer

const initialState = {
    loading: false,
    errors: null
}
export default function(state = initialState, action) {
    switch (action.type) {
      case 'SET_ERRORS':
        return {
          ...state,
          loading: false,
          errors: action.payload
        };
      case 'CLEAR_ERRORS':
        return {
          ...state,
          loading: false,
          errors: null
        };
      case 'LOADING_UI':
        return {
          ...state,
          loading: true
        };
        default:
            return state
    }
}

我真的很困惑我可以正常登录,但是状态没有更新,只有用户状态被初始化..

编辑: store.js

import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';

import userReducer from './reducers/userReducer';
import dataReducer from './reducers/dataReducer';
import uiReducer from './reducers/uiReducer';

const initialState = {};

const middleware = [thunk];

const reducers = combineReducers({
  user: userReducer,
  data: dataReducer,
  UI: uiReducer
});



const store = createStore(reducers, 
    initialState, 
    compose(
        applyMiddleware(...middleware),
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
);

export default store;

1 个答案:

答案 0 :(得分:0)

...action.payload 更改为 user: action.payload 似乎已修复它。我从一个教程中得到了本节的代码,但语法肯定有点过时了,谁知道

export default function(state = initialState, action){
    switch(action.type){
        case 'SET_AUTHENTICATED':
            return{
                ...state,
                authenticated: true
            }
        case 'SET_UNAUTHENTICATED':
            return initialState
        case 'SET_USER':
            return{
                authenticated: true,
                loading: false,
                user: action.payload
            }
        default:
            return state
    }
}