Ant*_*jac 3 node.js reactjs redux redux-thunk react-redux
我正在开发一个在后端使用 NodeJS 并在前端使用 React + Redux 的 CRUD 应用程序。这是所有内容如何工作的快速模式:
添加项目
POST在 NodeJS 中路由并通过正文发送标题后端完成,新帖子在服务器中
我.then()在第 2 步中添加了调度函数。在其中我使用type: 'ADD_POST'和调度了一个动作post: post(我从 NodeJS 得到了帖子res.json({post: result from database}))
在我的减速器中,我设置了一个 CASE 'ADD_POST': return action.post
前端完成,用户现在可以看到相同的帖子而无需刷新
我想使用相同的逻辑来更新特定帖子的喜欢。这是我到目前为止所做的:
PUT路由的调度后端完成,现在服务器中还有 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
}
})
Run Code Online (Sandbox Code Playgroud)
如果有帮助,这是我一直在看的播放列表,如果你愿意,你可以看看这家伙是如何实现删除功能的,我想使用相同的逻辑添加喜欢功能:链接到播放列表
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]
});
Run Code Online (Sandbox Code Playgroud)
Line[1]创建一个具有 的所有相同属性的新对象item,但它会覆盖现有属性likes并简单地添加1.
确保您实际上为减速器中更改的项目创建了一个新对象,因为您状态中的所有内容都应该是不可变的。
| 归档时间: |
|
| 查看次数: |
2148 次 |
| 最近记录: |