我的 react+redux 应用程序需要在商店中存储用户配置文件。示例数据:
{"user_id":11,"stuff":"more stuff"}, {"user_id":313,"stuff":"more stuff"},{"user_id":13111,"stuff":"more stuff"},{"user_id":21,"stuff":"more stuff"}
我应该如何将它存储在我的商店中?如果有帮助,我可以重新格式化上面的数据吗?
我需要 store.profiles 来存储 1 个或多个配置文件,它可能包括current_user的配置文件。
然后,我需要我的 Profile 组件能够在组件呈现时在存储区中找到或获取current_user的配置文件。我应该如何处理这个问题?
谢谢,我是 React+Redux 的新手
如果我在我的应用程序中设计配置文件,我会做一些类似于下面的代码的事情。在此方案中,我将用户保留在数组中。或者,您可以使用对象或地图。
// reducer
function userReducer(state = [], action) {
switch(action.type) {
// adding new user, just append to the end of array
case ADD_USER:
return [...state, {...action.payload.user }]
// editing an existing user, must check if exists! Othewise return original state
case EDIT_USER:
const filteredUsers = state.filter(user => user.id === action.payload.user.id);
const isUserExist = filteredUsers.length > 0;
if (isUserExist) {
const updatedUser = { ...filteredUsers[0], ...action.payload.user };
return [...state.filter(user => user.id !== action.payload.user.id), updatedUser];
} else {
return state;
}
default:
return state;
}
}
// sample user obj
{
id: 'unique-id',
first_name: 'bob',
last_name: 'jones',
email: 'test@mail.com',
photo_url: 'some url',
bio: 'some text'
}
// container.js
const mapStateToProps = (store) => ({
users: state.users,
getUser: (userId) => state.users.filter(user.id === userId),
});
const mapDispatchToProps = (dispatch) => ({
editUser: (userId) => dispatch(editUser(userId))
})
// actions.js
import uuid from 'uuid/v4';
function editUser(payload) {
return {
type: 'EDIT_USER',
...payload
}
}
function addUser(user) {
return {
type: 'ADD_USER',
payload : {
user: {
...user,
id: uuid()
}
}
}
}
// probably shouldn't edit id
payload {
id: 'uniquestring',
first_name: 'momo',
last_name: 'wawa',
// ... the rest of the changes
}
这假设您已经了解 redux 的基础知识。否则,请阅读本教程。