双重传播问题-摆脱Object.assign()

问题描述 投票:1回答:2

这是我的减速器主体代码片段:

const newState = {
    ...state,
    programs: {
        ...state.programs,
        ...Object.assign(
            {},
            ...action.payload.map(
                (channelName) =>
                    ({
                        [channelName]: {
                            ...state.programs[channelName],
                            selected: true
                        }
                    })
            )
        )
    }            
}
return newState

在这种情况下是否有机会摆脱Object.assign

[将Object.assign({}, a)更改为{ ...a }的经典建议在这种情况下不起作用,因为在这里我们已经有了...action.payload.map,因此它将导致... { ...a }进行扩展以产生类似于数组的键0, 1,2 ...

是否有任何优雅的方法可以正确转换我的代码?

javascript reactjs ecmascript-6 ecmascript-next
2个回答
2
投票

听说过reduce吗?

const action = {
  payload: ['discoveryChannel']
}

const state = {
  programs: {
    cartoonNetwork: {
      description: '',
      when: new Date()
    },
    discoveryChannel: {
      description: '',
      when: new Date()
    }
  }
}

const newState = {
  ...state,
  programs: {
    ...state.programs,
    ...action.payload.reduce(
      (acc, channelName) => {
        acc[channelName] = {
          ...state.programs[channelName],
          selected: true
        }

        return acc;
      }, {})
  }
}
console.log(newState);

0
投票

使用Object.fromEntries的另一种选择:

const action = {
  payload: ['discoveryChannel']
}

const state = {
  programs: {
    cartoonNetwork: {
      description: '',
      when: new Date()
    },
    discoveryChannel: {
      description: '',
      when: new Date()
    }
  }
}

const newState = {
  ...state,
  programs: {
    ...state.programs,
    ...Object.fromEntries(
         action.payload.map(
           channelName => ([
             channelName, {...state.programs[channelName], selected: true}
           ])
         )
       )
  }
}
console.log(newState);
© www.soinside.com 2019 - 2024. All rights reserved.