why my redux state not updating

自闭症网瘾萝莉.ら 提交于 2019-12-12 02:09:25

问题


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;
      }
    }

//component

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({ errors: err.response.data, isLoading: false }) );

  }

.....

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

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

回答1:


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;
      }
    }

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

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



来源:https://stackoverflow.com/questions/39544713/why-my-redux-state-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!