因此,我有一个名为getUserData
的操作,另外一个getAllUserData
的操作首先将仅获取登录用户的数据,其次将从DB中获取所有用户的数据。现在,我希望能够同时调用和发送。但是,如果我在getAllUserData
上调用getUserData
,则所有状态都会更改,getUserData
数据将丢失,并被getAllUserData
数据替换。我想两个都保留。有可能吗?
这是我的动作
export function getUserData(dispatch, getState) {
const state = getState();
const { user_id, token } = state.auth;
return axios.get(USER_DATA(user_id), {
headers: { authorization: token }
}).then((response) => {
dispatch(setBusinessData(response.data.data.userData[0]));
}).catch((err) => {
console.log("Couldn't get user data.");
});
}
export function getAllUserData(dispatch, getState) {
const state = getState();
const { token } = state.auth;
return axios.get(USER_ALL_DATA, {
headers: { authorization: token }
}).then((response) => {
let result = [];
response.data.map(o => {
result.push(o.userData);
});
merged = [].concat.apply([], result);
dispatch(setUserData(merged));
}).catch((err) => {
dispatch(console.log("Couldn't get all user data."));
});
}
这是我的减速器
module.exports = (state = [], action) => {
switch (action.type) {
case 'SET_USER_DATA':
return action.userData
case 'SET_BUSINESS_DATA':
return action.businessData
case 'UPDATE_USER_DATA':
return [
...state,
action.updatedUser
];
default:
return state;
}
}
编辑
这里是状态
Object {
"alerts": Array [],
"auth": Object {
"email": "user@mail.com",
"password": "password",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1YjI3NjAyNDAwOWI1NDA5ZjMwNzAzZWYiLCJpYXQiOjE1Mjk5MTQ0NjkwNjl9.r3hOOkx2I3qbVw_9ICRqsrSm9BLxUgachJgWax8MBDk",
"user_id": "5b276024009b5409f30703ef",
},
"userData": Object {
"_id": "5b2761be009b5409f30703f9",
"address": Array [
Object {
"_id": "5b2761be009b5409f30703fb",
"city": "London",
"number": "14",
"postcode": "N12 4NB",
"street": "Chantelham Road",
},
],
"businessData": Array [
Object {
"_id": "5b2761be009b5409f30703fa",
"position": "Hr Manager ",
"type": "Coffee company",
},
],
"education": Array [],
"experience": Array [],
"firstName": "Josh",
"lastName": "Wright",
"phone": 747489345,
"role": "employer",
"skills": Array [],
"volunteer": Array [],
},
}
在reducer中,我尝试为newState = []
创建一个'SET_USER_DATA'
,但是返回了错误
答案 0 :(得分:0)
您的状态应按用户ID访问用户,并跟踪当前登录的用户ID:
{
...
currentUserId: 'userId1',
userData: {
'userId1': { /* data of this user */ },
'userId2': { /* data of this user */ },
...
}
...
}
您也可以将其放在state.auth
中,这似乎已经包含当前用户ID。
这样,两个动作就不会相互干扰。但是,如果获取一个用户所产生的属性(针对该用户)比获取所有属性所产生的属性更多,则必须小心。