我想在我的 redux reducer 中创建一个新的 ES6 对象文字,它仅在操作包含特定属性时才覆盖键。
返回 { ...state, items: newItems, lastRefresh: action.meta && action.meta.timestamp }
如果 action.meta
或 action.meta.timestamp
未定义,此代码会将 lastRefresh
设置为 undefined
定义。
我知道长格式应该是这样的:
let result = {
...state,
items: newItems
}
if (action.meta && action.meta.timestamp) {
result.lastRefresh = action.meta.timestamp
}
return result
但它似乎过于冗长。 Object.assign
可能实现类似的功能吗?
最佳答案
如果您真正想要的是覆盖 state.lastRefresh:
return {
...state,
items: newItems,
lastRefresh: action.meta && action.meta.timestamp ? action.meta.timestamp : state.lastRefresh
}
关于javascript - 有条件地替换 redux reducer 中的状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44704882/