Javascript 更新redux状态

Javascript 更新redux状态,javascript,ecmascript-6,redux,Javascript,Ecmascript 6,Redux,我试图在更新状态时使我的redux还原程序更简单。例如,下面是一个减速器: const initialState = { emails: { id: { emailAddress: null, emailBody: null, emailSubject: null, }, }, calls: {}, }; function messaging(state = initialState, action) { switch (ac

我试图在更新状态时使我的redux还原程序更简单。例如,下面是一个减速器:

const initialState = {
  emails: {
    id: {
      emailAddress: null,
      emailBody: null,
      emailSubject: null,
    },
  },
  calls: {},
};

function messaging(state = initialState, action) {
  switch (action.type) {
    case actionTypes.SET_EMAIL_ADDRESS:
      return {
        ...state,
        emails: {
          ...state.emails,
          [action.id]: {
            emailAddress: [action.emailAddress]
          },
        },
      };
    default:
      return state;
  }
}

export default messaging;
我试着在下面写减速机,但是webstorm抱怨这不是正确的表示法。我做错了什么?此外,对于如何以更干净的方式更新状态的任何建议,我们都将不胜感激。谢谢

case actionTypes.SET_EMAIL_ADDRESS:
  return {
    ...state,
    emails[action.id]: {
      ...state.emails[action.id],
      emailAddress: [action.emailAddress]
    },
  };

您需要将动态键括在方括号内

case actionTypes.SET_EMAIL_ADDRESS:
  return {
    ...state,
    [state.emails[action.id]]: {
      ...state.emails[action.id],
      emailAddress: [action.emailAddress]
    },
  };

基于你的初始状态

并避免覆盖
emailBody
emailSubject
的现有值

我会这样重写:

case actionTypes.SET_EMAIL_ADDRESS:
    const currentEmails = state.emails;
    const emailId = action.id;
    const emailAddress = action.emailAddress;

    const email = { ...currentEmails[emailId], emailAddress };
    const emails = { ...currentEmails, [emailId]: email };
    return { ...state, emails };
使用描述性名称总是值得的

我已经开始使用when reducer来更改深度嵌套状态。例如

import produce from "immer";

function messaging(state = initialState, action) {
  switch (action.type) {
    case actionTypes.SET_EMAIL_ADDRESS:
      return produce(state, draft => {
        draft.emails[action.id] = { emailAddress: [action.emailAddress] };
      });
    default:
      return state;
  }
}

谢谢事实上,我认为应该是
[state.emails[action.id]]
顺便说一句。@Jimmy根据你的评论更新了答案。如果答案解决了你的问题,请接受。