Tho*_*nte 5 javascript reactjs redux normalizr
假设我有一个这样的结构,这是从API获取并在我的实体上使用"normalizr"的结果:
entities: {
users:{
1: {
name: 'John',
posts: [ 1, 4 ]
}
},
posts: {
1: {
name: 'First Post',
},
4: {
name: 'Second Post',
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个按用户过滤帖子的方法,基本上可以这样做:
let filteredPosts = {};
entities.users.posts.forEach(key => {
if(posts.hasOwnProperty(key))
filteredPosts[key] = posts[key]
});
Run Code Online (Sandbox Code Playgroud)
以及显示该用户帖子的页面,例如:
render() {
return(
<div>
{Object.keys(filteredPosts).map(key => {
return (
<div>{filteredPosts[key].name}</div>
);
})}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
我的实体reducer非常简单:
import { merge } from 'lodash';
...
function entities(state = { users: {}, posts: {} }, action) {
if (action.response && action.response.entities) {
return merge({}, state, action.response.entities);
}
return state;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我向API请求为该用户添加帖子,返回新创建的帖子记录,该记录将自动添加到我的实体上的帖子中.
我如何处理更新用户以反映该更改,以便用户现在有3个帖子,在数组中有新的帖子ID?
我应该创建一个reducer并听取post创建动作,并state.entities.users.posts在那里更新?重新获取实体似乎不是一种选择.最好的方法是什么?
谢谢
更新:
这是我现在必须使用的解决方案,以保持数据的一致性.我修改了对帐户创建的帖子ID的回复.我知道这可以分解为多个reducers,但我仍然想知道是否有更好更直接的方法,我不必为每个嵌套实体执行此操作.
function entities(state = {}, action) {
...
if(action.type === 'POST_ADD_SUCCESS') {
// Get the user id from the created post
let userId = response.entities.posts[response.result].userId;
// Add the user with all his posts to the response
response.entities.users = {
[userId]: {
posts: [...state.users[userId].posts, response.result]
}
}
}
...
// Merge normally
return merge({}, state, response.entities);
}
Run Code Online (Sandbox Code Playgroud)
您更新的代码片段看起来大部分都沿着正确的路径,尽管我不确定为什么您仍然在其中引用“响应”。您的操作创建器函数可能应该获取用户 ID 和帖子 ID,并且当 AJAX 调用成功时,创建一个类似于 的操作{type : POST_ADD_SUCCESS, userId : userId : postId}。换句话说,reducer 根本不应该知道有关“响应”的任何信息,只是应该将帖子 ID 'x' 添加到用户 ID 'y' 的列表中。
| 归档时间: |
|
| 查看次数: |
2602 次 |
| 最近记录: |