使用React + Redux,我应该如何在我的商店中存储个人资料?

时间:2017-06-19 05:26:55

标签: reactjs redux react-redux

我的react + redux app需要在商店中存储用户个人资料。示例数据:

{"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的个人资料。

然后我需要我的个人资料组件能够在组件渲染时在商店中查找或获取current_user的个人资料。我该怎么做呢?

谢谢,我是React + Redux的新手

1 个答案:

答案 0 :(得分:4)

如果我要在我的应用中设计个人资料,我会在下面的代码中执行类似操作。在这种情况下,我将用户保留在一个数组中。或者,您可以使用对象或Map

// 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的基础知识。否则,请阅读this tutorial