reactjs - 在 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()
方法用于连接两个或多个数组。此方法不会更改现有数组,而是返回一个新数组,其中包含连接数组的值。
解决方案
我会做
case 'GET_COMMENTS':
return ({
...state,
comments: state.comments.concat(action.payload.data),
next: action.payload.next
});
推荐阅读
- angular - 为什么 forkJoin 不适用于观察者?
- gulp - 使用 Gulp watch、Axios 和 Browsersync 在文件更改时重新加载浏览器之前进行 HTTP 获取
- python - 在自己的定义中运行 __init__
- azure - 如何使用 PowerShell 或 CLI 在 Azure 中获取应用服务的 clientID、clientSecret、subscriptionId、tenantId
- arrays - 如何使用这两个输入数组基于范围创建平铺/堆叠数组 - 但不循环?
- c# - .NET、C#、反射 GetMethod 返回 null(试图在第三方 dll 中获取方法)
- asp.net-core - “JsonConvert”类型中不存在类型名称“serializeObject”
- sql - 与前导零连接几个月 - 不是有效的月份错误
- spring - 如何在 SpringBoot 中测试 Kafka 客户端配置
- regex - Bash 从字符串中查找主题标签