更新嵌套的 redux 状态

Updating nested redux state

我有一个 reducer,它接收一个带有负载的动作,我需要用它来更新状态。问题是我需要在状态中更新的数据是嵌套数据。 我在下面添加了我的 reducer 并附上了一些评论以及我到目前为止尝试做的事情。

export default function(state=data, action){
  switch (action.type) {
    case 'UPDATE_CONTACT_INFO':
      let appointment = state[action.appointmentIndex]; // This is the appointment that needs to be updated 
      appointment.notification.contactInfo = action.payload; // this is the data that needs to be updated with the payload. I tried updating it like this but then not sure how to add it to the state. 
      return state; // Somehow need to update the state with the new state
      break;
    default:
    return state;
  }
}

下面是我的初始数据结构,我将其作为默认状态传递给 reducer。

 data = [
        {
        date: 'Friday, January 6',
        time: '4:00 PM-5:00 PM',
        notification:
          {
            contactInfo: [
              {
                displayMethod:"Phone Call",
                method:"Phone",
                value:"3473686552"
              },
              {
                displayMethod:"Email",
                method:"Email",
                value:"memedoe@gmail.com"
              }
            ]
          }
      },
      {
        date: 'Saturday, January 7',
        time: '2:00 PM-6:00 PM',
        notification:
          {
            contactInfo: [
              {
                displayMethod:"Phone Call",
                method:"Phone",
                value:"2123686552"
              },
              {
                displayMethod:"Email",
                method:"Email",
                value:"johndoe@gmail.com"
              }
            ]
          }
      }
    ];

reducer 数据中的 action.payload 与其中一个约会中的 contactInfo 数组结构相同。 [Object, Object]

使用 redux,你永远不会更新状态。您将必须 return 一个新的状态对象,其中包含更新后的数据。

为此,您需要使用 Object.assign() 或 ES6 扩展运算符 {...}

我已经提供了两者的链接: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

在此处阅读减速器: http://redux.js.org/docs/basics/Reducers.html

特别注意我们不改变状态点。

您需要使用object.assign更改您商店中的数据

const newstateobject = Object.assign({}, state[someIndex], {notification: Object.assign({}, state[someindex].notification, {contactInfo: action.payload})});

return Object.assign({}, state, {[someindex]: newstateobject);

所有此类问题都可以使用 react-addons-update 包解决。阅读 here.

这个案例可以这样解决:

export default function(state=data, action){
  switch (action.type) {
    case 'UPDATE_CONTACT_INFO':
      return update(state, {[action.appointmentIndex]:{notification: {contactInfo: {$set: action.payload}}}});
    default:
    return state;
  }
}