[英]Can't get state to update array inside of an object correctly in REACT/REDUX
我将针对我想发生的事情逐步分解,希望人们能够理解我想要的。
使用React / Redux,Lodash
我有很多帖子是从后端api作为数组发送的。 每个帖子都有一个_id
。 当我调用动作getAllPost()
它会将所有帖子都带回给我。 这很好。
然后,我分派类型GET_ALL_POSTS
,它触发reducer_posts
更改/更新状态。
减速器:
export default function(state = {}, action) {
switch(action.type) {
case GET_ALL_POSTS:
const postsState = _.mapKeys(action.payload.data, '_id');
//const newPostsState = _.map(postsState, post => {
//const newComments = _.mapKeys(post.comments, '_id');
//});
return postsState;
break;
default:
return state;
break;
}
}
例:
BigPostsObject {
1: SinglePostObject{},
2: SinglePostObject{},
3: SinglePostObject {
_id: '3',
author: 'Mike',
comments: BigCommentObject{1: SingleCommentObject{}, 2: SingleCommentObject{}}
}
}
我希望这个例子能弄清楚我要做什么。 如果仍然对我在做什么感到困惑,请询问,也不要说使用数组代替之类的事情。 我知道我可以使用数组,但是这对这篇文章没有帮助,就好像其他人希望以此方式做也是有用的信息。
我相信如今,JS内置函数无需外部库即可完成此操作。 无论如何,这应该是要走的路。 我真的会鼓励您回到js内置函数。
var data = [
{
_id: '3',
title: 'Going on vaccation',
comments:[
{_id: 1, comment: 'hello'},
{_id: 2, comment: 'world'}
]
},
{
_id: '2',
title: 'Going to dinner',
comments:[
{_id: 1, comment: 'hello'},
{_id: 2, comment: 'world'}
]
}
]
//you can use JS builtin reduce for this
var transformedPost= _.reduce(data, function(posts, post) {
var newPost = Object.assign({}, post)
newPost._id=post._id
//you can use js builtin map for this
newPost.comments = _.mapKeys(post.comments, '_id')
// if you are using es6, replace the last three line with this
//return Object.assign({}, posts, {[newPost._id]: newPost})
var item = {}
item[newPost._id]=newPost
return Object.assign({}, posts, item)
},{});
console.log(transformedPost)
编写一个函数,为您在posts数组中的每个帖子处理来自评论数组的所有评论:
function processComment(post) {
post.bigCommentsObject = _.mapKeys(post.comments, '_id');
// now the comments array is no longer needed
return _.omit(post, ['comments']);
}
现在,使用该函数将每个注释数组变成具有所有注释的大对象,尽管它仍在数组中。 然后,将数组本身放在一个大对象中:
const commentsProcessed = _.map(action.payload.data, procesComment);
const postsState = _.mapKeys(commentsProcessed, '_id');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.