【问题标题】:Redux - Adding element to array nested in an object inside an arrayRedux - 将元素添加到嵌套在数组内的对象中的数组
【发布时间】:2017-11-28 03:29:38
【问题描述】:

无法弄清楚如何正确地将元素插入到数组中,即在对象内部,在数组内部。这是我的结构默认数据示例:

const defaultState = {
  myinbox: [
    {
      owner: 'John Lennon',
      owner_id: 1,
      read: true,
      messages: [
        {
          _id: 1,
          text: 'When will you be home?',
          createdAt: new Date(Date.UTC(2017, 10, 11, 11, 20, 0)),
          user: {
            _id: 1,
            name: 'John Lennon'
          }
        }
 ...

当有入站消息进来时,我想添加另一条消息。这就是我的 reducer 中的 sn-p 的样子:

const inboxReducer = (state = defaultState, action) => {
  switch (action.type) {
    case 'ADD_INBOUND_MESSAGE':
      return {
        ...state,
        myinbox: [
          state.myinbox[action.payload.index]: {
            ...state.myinbox[action.payload.index],
            messages: [
              ...state.myinbox[action.payload.index].messages,
              action.payload.msg
            ]
          }
          ...state.myinbox,
        ]
      }
  default:
    return state
  }
}

父“所有者”的索引作为有效载荷内部的索引传递,新消息是有效载荷中的msg。

如果不改变原始状态,我不知道如何编写这个 reducer。

【问题讨论】:

    标签: arrays redux react-redux


    【解决方案1】:

    当您使用state.myinbox[action.payload.index]: 设置myinbox 时,您正在改变原始状态。

    您似乎正在尝试使用computed property keys 设置索引的状态。其语法为:

        myinbox: [
          [action.payload.index]: {
            ...state.myinbox[action.payload.index],
            messages: [
              ...state.myinbox[action.payload.index].messages,
              action.payload.msg
            ]
          }
          ...state.myinbox,
        ]
    

    【讨论】:

      【解决方案2】:

      这可以通过Immer完成

        const { index, msg } = action.payload;
        return produce(state, (draftState) => {
          draftState.myinbox[index].messages.push(msg);
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-22
        • 1970-01-01
        相关资源
        最近更新 更多