为什么我的redux状态没有更新 [英] why my redux state not updating

查看:215
本文介绍了为什么我的redux状态没有更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

状态未更新.当分派动作时,状态应更新为isAuthenticated为true ..但是状态未更新..redux返回初始状态而不是更新后的状态.

state not updating.when action is dispatched the state should update to isAuthenticated to true..but the state not updating..redux returning the initial state not the updated state.

export function setCurrentUser(user) {
      console.log(user);
      return {
        type: "SET_CURRENT_USER",
        user
      };
    }

   ...
    export function login(userData) {
      return dispatch => {
        return axios.post('/user/auth',userData).then((res) => {
          const { status, sessionId, username, error} = res.data;
          if(status === "success"){
            dispatch(setCurrentUser(sessionId));
          }else {
            dispatch(invalidUser(error));
          }
        });
      }
    }

//reducers

    import { SET_CURRENT_USER, INVALID_USER } from "../actions/types";
    import isEmpty from "lodash/isEmpty";

    const initialState = {
      isAuthenticated : false,
      user: {},
      error:{}
    };

    export default (state = initialState, action) => {
      switch(action.type){
        case SET_CURRENT_USER:
        return {
          ...state,
         isAuthenticated: !isEmpty(action.user),
         user:action.user
        }
        ...
        default: return state;
      }
    }

//组件

onSubmit(e){
    e.preventDefault();
      this.setState({ errors: {}, isLoading:true });
      this.props.login(this.state).then(
      (res) => {
        console.log(this.props.userData);
        if(this.props.userData.isAuthenticated)
          this.context.router.push("greet");
        },

(err)=> this.setState({错误:err.response.data,isLoading:false}) );

(err) => this.setState({ errors: err.response.data, isLoading: false }) );

  }

.....

function mapStateToProps(state) {
  return {
    userData: state.authReducers
  };
}

export default connect(mapStateToProps, { login })(LoginForm);

推荐答案

您不更新减速器中的有效载荷数据

You are not updating the payload data in your reducer

export default (state = initialState, action) => {
      switch(action.type){
        case SET_CURRENT_USER:
        return {...state, user: action.payload} //update user here
        }
        ...
        default: return state;
      }
    }

上面的代码使用了es6功能,并且假设isAuthenticatederror是初始状态的一部分.

the above code uses es6 features and the assumption made is isAuthenticated and error are part of the initial state.

您只是返回相同的JSON,这就是您的状态未更新的原因.

You are just returning the same JSON which is why your state is not updating.

这篇关于为什么我的redux状态没有更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆