[英]How to store and update deeply nested structures in ImmutableJS
我正在用react + redux建立一個小博客,但我想不出該如何回復博客文章下的評論。 我正在為一篇看起來像這樣的博客帖子獲取評論結構。
"[
{"_id":"5676ed8b9104691f3b85b687",
"content":"Lorem",
"creator":"Admin",
"replies":[
{
"_id":"5676ede4b7a9044c3c1d9641",
"content":"Ipsum",
"creator":"Admin",
"replies":[
{
"_id":"5676eec224ab8fe23c7ce4c6",
"content":"Dolor",
"creator":"Admin",
"replies":[]
},
{
"_id":"5676eeda1c0e3d093d1f90a0",
"content":"Sit",
"creator":"Admin",
"replies":[]
}
]
},
{
"_id":"5676ee5b4b03bbac3c1f7544",
"content":"Amet",
"creator":"Admin",
"replies":[]
},
{
"_id":"5676ee91c43c05c63c319ace",
"content":"Sup",
"creator":"Admin",
"replies":[]
}
]},
{...}
]
如何將其存儲在ImmutableJS狀態下,以便可以基於_id
輕松添加評論的回復? 另外,注釋必須是可迭代的,因為之后我會將它們渲染到注釋樹中,但是只要使用ImmutableJS數據結構,我認為這不會成為問題。 基本上我不知道如何在我的減速器中實現此功能。
[REPLY_COMMENT]: (state, { payload }) => {
const { _id, comment } = payload
let newState = ???
return newState
}
編輯
這是jsbin,顯示我要實現的目標。 我只希望能夠回復所有評論
你得把這個分解一下。
因此,首先讓我們將注釋添加到Immutable.Map
state = state.update('coolPostId', post => Immutable.fromJS(comments));
const replyToPostComment = {
_id: '1234',
content: 'Hello',
creator: 'RandomUser',
replies: []
};
現在,在coolPostId
下有一個Immutable.List
,因此您想通過push
新注釋來update
該列表:
state = state.update('coolPostId', comment => comment.push(Immutable.fromJS(replyToPostComment)));
這將通過您的第一個測試:
const expected = state.get('coolPostId').last();
expect(expected.toJS()).to.deep.equal(replyToPostComment);
第二部分同樣簡單,但是您需要映射注釋,並檢查_id
與您的元數據匹配。
這是您的設置:
const replyComment = {
_id: '5678',
content: 'Wellcome',
creator: 'RandomUser2',
replies: []
};
const reply = {
postId: 'coolPostId',
commentId: '1234',
comment: replyComment
};
下一行取決於將執行_id
檢查的函數,
state = state.get(reply.postId)
.map(comment => addReply(comment)(reply));
最后一個難題是addReply
謂詞:
const addReply = c => cr => c.get('_id') === cr.commentId ? c
.update('replies', replies => replies.push(Immutable.fromJS(cr.comment)) ) : c;
這是完整的jsbin可供審查
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.