Redux - 通过其键在状态数组中查找 object 并更新其另一个键
Redux - Find object in state array by its key and update its another key
我正在开发一个 CRUD 应用程序,在后端使用 NodeJS,在前端使用 React + Redux。这是其中所有内容如何工作的快速模式:
添加项目
- 用户输入post
的标题
- 然后将标题发送到 dispatch,它在 NodeJS 中获取
POST
路由并通过 body 发送标题
- 在 NodeJS 路由中,我在 collection 中添加了一个具有该标题的新项目
后端完成,新 post 在服务器中
我在第 2 步的调度函数中添加了 .then()
。其中我使用 type: 'ADD_POST'
和 post: post
调度了一个动作(我得到了 post 来自 NodeJS res.json({post: result from database})
)
在我的reducer中我设置了一个CASE 'ADD_POST': return action.post
前端完成,相同的 post 现在无需刷新即可对用户可见
我想使用相同的逻辑来更新特定 post 的 赞 。这是我到目前为止所做的:
- 单击 post 上的按钮会触发获取 NodeJS
PUT
路由的调度
- NodeJS 路由使用 ID 找到 post 并将 1 加到 likes the post had
的旧值
后端完成,post 现在服务器中有 1 个赞
我再次将 .then
添加到获取 NodeJS 路由的分派中,在该分派中我使用更新的 type 'ADD_LIKE'
和 post ID
分派一个动作
在 reducer 中,我设置了一个 CASE 'ADD_LIKE':
,它使用以下代码段中的代码遍历状态。
这是该片段:
state.map(item => {
if(item.id === action.postid) {
//i find the specific item, but now im stuck on how to update the likes property of it
}
})
如果有帮助,这是我一直在看的播放列表,如果你愿意,你可以看看这个人如何实现删除功能,我想使用相同的逻辑添加喜欢功能:Link to playlist
state.map(item => {
if (item.id !== action.postid) return item; // no need to change other items
const likes = item.likes;
return Object.assign({}, item, {likes: likes + 1}); // [1]
});
第 [1]
行创建了一个具有 item
所有相同属性的新对象,但它覆盖了现有的 属性 likes
并简单地添加了 1
.
确保您确实为 reducer 中的更改项创建了一个新对象,因为您状态中的所有内容都应该是不可变的。
我正在开发一个 CRUD 应用程序,在后端使用 NodeJS,在前端使用 React + Redux。这是其中所有内容如何工作的快速模式:
添加项目
- 用户输入post 的标题
- 然后将标题发送到 dispatch,它在 NodeJS 中获取
POST
路由并通过 body 发送标题
- 在 NodeJS 路由中,我在 collection 中添加了一个具有该标题的新项目
后端完成,新 post 在服务器中
我在第 2 步的调度函数中添加了
.then()
。其中我使用type: 'ADD_POST'
和post: post
调度了一个动作(我得到了 post 来自 NodeJSres.json({post: result from database})
)在我的reducer中我设置了一个
CASE 'ADD_POST': return action.post
前端完成,相同的 post 现在无需刷新即可对用户可见
我想使用相同的逻辑来更新特定 post 的 赞 。这是我到目前为止所做的:
- 单击 post 上的按钮会触发获取 NodeJS
PUT
路由的调度 - NodeJS 路由使用 ID 找到 post 并将 1 加到 likes the post had 的旧值
后端完成,post 现在服务器中有 1 个赞
我再次将
.then
添加到获取 NodeJS 路由的分派中,在该分派中我使用更新的type 'ADD_LIKE'
和post ID
分派一个动作在 reducer 中,我设置了一个
CASE 'ADD_LIKE':
,它使用以下代码段中的代码遍历状态。
这是该片段:
state.map(item => {
if(item.id === action.postid) {
//i find the specific item, but now im stuck on how to update the likes property of it
}
})
如果有帮助,这是我一直在看的播放列表,如果你愿意,你可以看看这个人如何实现删除功能,我想使用相同的逻辑添加喜欢功能:Link to playlist
state.map(item => {
if (item.id !== action.postid) return item; // no need to change other items
const likes = item.likes;
return Object.assign({}, item, {likes: likes + 1}); // [1]
});
第 [1]
行创建了一个具有 item
所有相同属性的新对象,但它覆盖了现有的 属性 likes
并简单地添加了 1
.
确保您确实为 reducer 中的更改项创建了一个新对象,因为您状态中的所有内容都应该是不可变的。