在下面的reducer文件中,当用户登录时,状态将使用来自操作文件的有效负载进行更新。在我的状态下,我有一个用户对象,我想在其中存储有效负载。然而,在我的redux-dev工具中,我注意到负载出现在用户对象之外,而不是它内部,因此用户对象显示为默认值null。搞不清我做错了什么。
//登录还原器填充
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
});
});
};
您需要将LOGIN_SCCESS用例块中的reducer返回方法更改为这个
return {
...state,
user:action.payload,
isAuthenticated: true,
isLoading: false
};