这是我的减速器主体代码片段:
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 ...
是否有任何优雅的方法可以正确转换我的代码?
听说过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);
使用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);