このような構造があるとしましょう。これは、API から 1 回フェッチし、エンティティで「normalizr」を使用した結果です。
entities: {
users:{
1: {
name: 'John',
posts: [ 1, 4 ]
}
},
posts: {
1: {
name: 'First Post',
},
4: {
name: 'Second Post',
}
}
}
これで、ユーザーごとに投稿をフィルタリングするメソッドができました。これは基本的に次のことを行います。
let filteredPosts = {};
entities.users.posts.forEach(key => {
if(posts.hasOwnProperty(key))
filteredPosts[key] = posts[key]
});
そして、そのユーザーからの投稿を表示するページ。例:
render() {
return(
<div>
{Object.keys(filteredPosts).map(key => {
return (
<div>{filteredPosts[key].name}</div>
);
})}
</div>
)
}
私のエンティティリデューサーは非常にシンプルです:
import { merge } from 'lodash';
...
function entities(state = { users: {}, posts: {} }, action) {
if (action.response && action.response.entities) {
return merge({}, state, action.response.entities);
}
return state;
}
そのユーザーの投稿を追加するように API に要求すると、新しく作成された投稿レコードが返され、そのレコードがエンティティの投稿に自動的に追加されます。
その変更を反映するようにユーザーを更新して、ユーザーが配列に新しい投稿 ID を持つ 3 つの投稿を持つようにするにはどうすればよいでしょうか?
レデューサーを作成して作成後のアクションをリッスンし、state.entities.users.posts
そこで更新する必要がありますか? エンティティを再取得することは選択肢のようには見えません。そのための最善の方法は何ですか?
ありがとう
アップデート:
これは、データの一貫性を保つために現在使用しなければならないソリューションです。作成された投稿 ID を考慮して応答を変更します。これは複数のレデューサーに分解される可能性がありますが、ネストされたエンティティごとにこれを行う必要がない、より直接的なアプローチがあるかどうかはまだ疑問です。
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);
}