干净的添加用户的方式(如果不存在)

时间:2019-12-11 12:02:37

标签: angular ionic-framework redux ngrx

如果该用户不存在,我想将一个用户添加到我的用户数组中,但是如果该用户不存在,则我不想更改任何内容。通常,我会这样做:

users: {...state.users, newUser}

但这是不可能的,因为在这种情况下我没有属性名称。

所以我的用户是这样的:

export interface IUser {
  username: string;
  deviceCode: string;
  deviceName: string;
}

state.users: IUser[];

我为解决这个问题所做的是:

case AuthActionTypes.REGISTER_SUCCESS: {
  const currentUser: IUser = {
    username: state.username,
    deviceCode: action.payload.deviceCode,
    deviceName: action.payload.deviceName,

  };

  const userExists = state.users.find((user) => user.username === state.username);
  let users = state.users;
  if (!userExists) {
    users = {...state.users, ...[currentUser]}
  }
  return {
    ...state,
    deviceCode: action.payload.deviceCode,
    deviceName: action.payload.deviceName,
    users,
  };
}

问题在于它对我来说还不够干净,而减速器应始终尽可能干净。有没有办法使users: {...state.users, newUser}工作?如果没有,还有其他好的方法吗?

简而言之:

case AuthActionTypes.REGISTER_SUCCESS: {
  // I don't want to write any code here
  return {
    ...state,
    deviceCode: action.payload.deviceCode,
    deviceName: action.payload.deviceName,
    users: {...state.users, newUser}, // Add new user if it doesn't exist, 
                                      // Change if it is different 
                                      // Do nothing if it is the same
  };
}

1 个答案:

答案 0 :(得分:0)

我发现正确的方法的最好方法是:

case AuthActionTypes.REGISTER_SUCCESS: {
  const currentUser = [];
  currentUser[state.username] = {
    deviceCode: action.payload.deviceCode,
    deviceName: action.payload.deviceName,

  };
  return {
    ...state,
    deviceCode: action.payload.deviceCode,
    deviceName: action.payload.deviceName,
    users: {...state.users, ...currentUser}
  };
}

由于属性名称现在等于用户名,所以我总是可以将其分配给用户名(如果不存在该用户名,则添加该名称),如果不相同则进行编辑,如果相同则不执行任何操作。

我认为这个答案使我的问题更加具体,因此,如果您有更好的答案,我会很乐意接受。