在化简器中处理更新状态的更好方法



所以我正在尝试学习react-redux和我的化简器GET_COMMENTS.我需要首先检查state.comments中是否已经有项目,所以我尝试使用if-else语句并且它有效。但也许还有更好的处理方法?

case 'GET_COMMENTS':
let list = []
if (state.comments.length > 0) { // check if there's an item 
list = state.comments // pass existing state
action.payload.data.map(comment => { // map through new data
list = [...list, comment] // dont know if this is the right way but it works
})
} else {
list = action.payload.data // if state.comments is empty directly pass new data
}
return {
...state,
comments: list,
next: action.payload.next
}

更新:我决定选择Gabriele答案,因为我认为这是最好的方法。今天我了解到.concat()方法用于连接两个或多个数组。此方法不会更改现有数组,而是返回一个新数组,其中包含联接数组的值。

我会做的

case 'GET_COMMENTS':
return ({
...state,
comments: state.comments.concat(action.payload.data),
next: action.payload.next
});

是的,这是正确的。我会简化你的方法

...
case 'GET_COMMENTS':
return {
...state,
comments: [...state.comments, ...action.payload.data]
next: action.payload.next
};

注意:我认为action.payload.comments是一组新的评论。初始状态为{ comments: [] }.

最新更新