当componentDidMount我发送一个动作来发送请求时,这是下面的动作代码。 receiveUserInfo只是将数据返回到reducer
export function requestUserInfo() {
return dispatch => {
dispatch(getUserInfo())
return axios.post('/user/getScores', qs.stringify({
token: token,
uid: uid
}))
.then(res => {
if (res.data.status !== 200) {
message.error(res.data.message)
return state
}
// return the data from server
return { ...res.data.attachment}
})
.then(data => {
// receiveUserInfo just return action and data
dispatch(receiveUserInfo(data))
})
}
}
这是reducer代码。
const token = localStorage.getItem('token')
const uid = localStorage.getItem('uid')
export const requestUserInfo = (state = {}, action) => {
switch (action.type) {
case 'HEADER_GET_USERINFO':
case 'HEADER_RECEIVE_USERINFO':
return Object.assign({}, state, action.data)
break
default:
return state
}
}
function receiveUserInfo(data) {
return {
type: 'HEADER_RECEIVE_USERINFO',
data
}
}