redux 如何编辑数组中对象的userAccount

jdgnovmf  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(144)

请帮助我解决这个问题。
我正在制作一个注册表,然后用户可以通过Redux编辑他们的信息,我有一个问题,编辑用户帐户信息(如姓名,电子邮件,通行证...)
我已经尝试了下面的代码,但是它返回了一个未定义的状态,并且没有任何改变。我有一个如下的initialState:

const initialState = {
  userAccounts: [
    {
      id: new Date().getTime(),
      fullname: 'userName',
      email: 'userEmail',
      pass: 'userPass',
    },
  ],
};

下面是我的行动和减速器:

export const editAccount = (param) => (
    {
        type: EDIT_ACCOUNT,
        payload: param
    }
)


const registerReducer = (state = initialState, action) => {
  
  switch (action.type) {
      
        case REGISTER:
            return {
                ...state,
                userAccounts: [...state.userAccounts, action.payload],
            };
            
        case EDIT_ACCOUNT:
            return state.userAccounts.map((account, i) => {
                if (account.id === action.payload.id) {
                    return {
                      ...state.userAccounts[i],
                      fullname: action.payload.fullname
                    };
                }
            });
        default:
        return state;

  }
};

这是我在编辑屏幕上的派遣代码

const handleChangeInfo = () => {
      let accIndex = userAccounts.findIndex(item => item.fullname === params.name)
      dispatch(editAccount({
        id: userAccounts[accIndex].id,
        fullname: value,
      }))
      navigation.goBack()
  }
x33g5p2x

x33g5p2x1#

您可以在注册表中尝试此操作Reducer

case EDIT_ACCOUNT:
let userArr = [];
state.userAccounts.map((account, i) => {
  if (account.id === action.payload.id) {
    userArr.push({
      ...account,
      fullname: action.payload.fullname
    })
  } else {
    userArr.push(account);
  }

});
return {
  ...state,
  userAccounts: [...userArr],
};

相关问题