簡體   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