根据过滤的数组检索数据



我正在尝试过滤一个基于 post.id 比较的数组,检索值并将其附加到 likes 属性。

action.data.filter((post) => post.id === action.id).Likes.length

不像我想象的那样工作,给我一个未定义长度的错误

如果我做类似的事情

 action.data.filter((post) => post.id === 5)

它会给我我想要的结果,但这行不通,它需要动态的。

return {
  ...state, 
  posts: action.data, // maps posts fine,
  likes: action.data.filter((post) => post.id === action.id).Likes.length // does not do what i want it do :(
 }

它应该是动态的,以便该特定帖子的任何值都有其自己的价值。我应该做什么或有什么解决方案?

当它被称为{this.props.likes}

action.id(获取现有帖子 ID(

console.log(action.id)

输出此

[5,2]

发布数据输出此

(2) [{…}, {…}]
 0:
  Likes: (32) 
  createdAt: "2019-04-26T09:38:10.324Z"
  id: 5
  post_content: "ssss"
  title: "React Interview Questionsdd"
  updatedAt: "2019-04-26T09:38:10.324Z"
  userId: 1
  username: "owlmans"
  __proto__: Object
 1: {id: 3, title: "React Interview sssQuestions", post_content: "ggg", 
  username: "owlman", createdAt: "2019-04-24T20:48:36.710Z", …}
  length: 2
  __proto__: Array(0)

操作.js

export const GetPosts = () => {
    return (dispatch, getState) => {
        return Axios.get('/api/posts/myPosts')
            .then( (res) => {
                 const data = res.data
                 const id = data.map( (post) => post.id)  // gets posts id [5,3]
                 dispatch({type: GET_POSTS, data, id})
             })
    }
}

过滤器返回过滤数据的数组.. 所以当你过滤访问零索引以检索喜欢长度

对于点赞的总和:

    action.data.filter((post) => action.id.includes(post.id)).reduce((a,b) => {
     return a.Likes.length + b.Likes.length
    })

对于分散的喜欢:

    action.data.filter((post) => action.id.includes(post.id)).map((a) => {
     return { postlikes: a.Likes.length }
    })

有关更多详细信息,请阅读过滤器

所以你想知道帖子的总喜欢吗? 还是每个帖子的总赞数?

因此,如果您想获得喜欢的总和,您可以使用"减少"。

在此处查看文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

此外,看起来并非每个对象都有喜欢的要点,因此您必须检查它。

let totalNumberOfLikes = action.data.posts.reduce( acc, post =>{
 if(post.id == action.id && post.hasOwnProperty('Likes'){
    acc += post.Likes.length
 }
} , 0 );

return {
  ...state, 
  posts: action.data,
  likes: totalNumberOfLikes }

如果你想为你几乎在那里的每个帖子获得喜欢,请记住,filter返回一个数组,因此您正在检查过滤帖子数组Likes的属性。

您要做的是检查每个帖子的属性Likes,而不是过滤帖子的数组。

所以代替: action.data.filter((post) => post.id === action.id).Likes.length .你可以做这样的东西:

let filteredPosts = action.data.posts.filter( post => post.id == action.id );
let totalLikesForEachPost  =  {}; 
//Here you need an object to keep the record of every like in the post if this has any and an id so you can access the data.
filteredPosts.forEach( post => {
  totalLikesForEachPost[ post.id ] = {  
       totalLikes: post.hasOwnProperty('Likes') ? post.Likes.length : 0,
       id: post.id,
  }
} );

return {
  ...state, 
  posts: action.data,
  likes: totalLikesForEachPost }

试试这个

const filtered = action.data.filter((post) => action.id.includes(post.id))
return filtered.map((post,index) => `post ${index} has ${post.Likes.length} likes`)

最新更新