首页 > 解决方案 > 在 reducer 中处理更新状态的更好方法

问题描述

所以我正在努力学习react-redux并在我的 reducerGET_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()方法用于连接两个或多个数组。此方法不会更改现有数组,而是返回一个新数组,其中包含连接数组的值。

标签: reactjsreduxreact-redux

解决方案


我会做

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

推荐阅读