繁体   English   中英

无法在REACT / REDUX中获得状态以正确更新对象内部的数组

[英]Can't get state to update array inside of an object correctly in REACT/REDUX

我将针对我想发生的事情逐步分解,希望人们能够理解我想要的。

使用React / Redux,Lodash

  1. 我有很多帖子是从后端api作为数组发送的。 每个帖子都有一个_id 当我调用动作getAllPost()它会将所有帖子都带回给我。 这很好。

  2. 然后,我分派类型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;
  }
}
  1. 如您所见,我将数组更改为一个巨型对象,该对象包含许多帖子,这些帖子的键等于其“ _id”。 这很好,返回该状态的一部分也很好。
  2. 正如我提到的,这些帖子中的每个帖子都有一个数组的comment值。 我想将注释数组更改为一个大对象,该对象将每个注释作为一个对象,其键等于其“ _id”,就像我在帖子中所做的那样。
  3. 现在,我需要立即执行所有操作,并使用一个包含所有帖子作为对象的大对象返回新创建的状态,并且在每个帖子上都应该有一个注释对象,该对象将所有注释作为对象。 我将尝试编写一些示例代码来显示我要执行的操作。

例:

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)

https://jsbin.com/suzifudiya/edit?js,console

编写一个函数,为您在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM