React和Redux:有效负载未出现在Reducer状态对象内

时间:2020-11-12 20:59:44

标签: javascript reactjs redux react-redux axios

在以下的reducer文件中,当用户登录时,状态数据将更新为来自动作文件的有效负载。在我的状态下,我有一个要在其中存储有效负载的用户对象。但是,在我的redux开发工具中,我注意到有效负载出现在用户对象外部而不是内部,结果用户对象显示为默认值null。无法弄清楚我在做什么错。

// Login Reducer Fille

const initialState = {
  token: localStorage.getItem('token'),
  isAuthenticated: false,
  isLoading: false,
  user: null
};

export default function(state = initialState, action){
  switch(action.type){
    case LOGIN_SUCCESS:
    localStorage.setItem('token', action.payload.token);
    return{
      ...state,
      ...action.payload,
      isAuthenticated: true,
      isLoading: false
    };
    default:
      return state;
  }
}

//登录操作文件

export const login = ({email, password, history}) => dispatch =>{
  const config = {
    headers:{
      "Content-Type": "application/json"
    }
  };

 
  const body = JSON.stringify({email, password});
  axios.post('/api/user/login/', body, config)
    .then(res => {
      console.log(res.data)
      dispatch({
      type: LOGIN_SUCCESS,
      payload: res.data
    })
    history.push('/dashboard')
  })
    .catch(err =>{
      dispatch(returnErrors(err.response.data, err.response.status, 'LOGIN_FAIL'));
      dispatch({
        type: LOGIN_FAIL
      });
    });
};

1 个答案:

答案 0 :(得分:0)

您需要将LOGIN_SUCCESS案例块中的reducer返回方法更改为此

return {
  ...state,
  user:action.payload,
  isAuthenticated: true,
  isLoading: false
};