Reactjs 如何添加映射函数返回的项目 getTotalUserVotes=(userid)=>{ 让posts=this.state.posts.slice(); let current=posts.filter((项目)=>{ return item.userid==userid; }) console.log(当前); const tot=当前.map((项目)=>{ 返回项目。投票; }) 日志(“tot为”+tot) //这记录了50,0,0 //因此,属于该用户的三篇文章中的每一篇都有这些数量 //投票数。我如何添加这些? 返回票:{tot}; }

Reactjs 如何添加映射函数返回的项目 getTotalUserVotes=(userid)=>{ 让posts=this.state.posts.slice(); let current=posts.filter((项目)=>{ return item.userid==userid; }) console.log(当前); const tot=当前.map((项目)=>{ 返回项目。投票; }) 日志(“tot为”+tot) //这记录了50,0,0 //因此,属于该用户的三篇文章中的每一篇都有这些数量 //投票数。我如何添加这些? 返回票:{tot}; },reactjs,Reactjs,当我尝试使用for循环来添加这些字符串时,我得到了5000个字符串,我搜索了如何阻止堆栈溢出,但没有一个答案与我的情况有任何关系。 POST中数据的一个例子是 您可以使用reduce方法而不是map来添加每个项目的投票 getTotalUserVotes = (userid) => { let posts = this.state.posts.slice(); let current = posts.filter((item) => { return item.us

当我尝试使用for循环来添加这些字符串时,我得到了5000个字符串,我搜索了如何阻止堆栈溢出,但没有一个答案与我的情况有任何关系。

POST中数据的一个例子是

您可以使用reduce方法而不是map来添加每个项目的投票

getTotalUserVotes = (userid) => {
  let posts = this.state.posts.slice();
  let current = posts.filter((item) => {
    return item.userid === userid;
  })
  console.log(current);
  const tot = current.map((item) => {
    return item.votes;
  })

  console.log("tot is " + tot) 
// this logs 50, 0 ,0 
//so each of the three posts that belong to that user have those amount
//of votes respectively.How can I add these? 
  return <div>votes: {tot}</div>;
}
但是,您实际上可以一次过滤、映射和减少所有内容

const tot = current.reduce((total, item) => total + Number(item.votes), 0);
const getTotalUserVotes=(userid)=>{
const tot=this.state.posts.reduce((总计,post)=>{
return post.userid==userid?总数+票数(post.voces):总数
}, 0)
返回票:{tot};
}

您可以将
项转换为一个数字(因为听起来像是存储为字符串),然后使用for循环或求和值:

const getTotalUserVotes = (userid) => {

    const tot = this.state.posts.reduce((total, post) => {
        return post.userid === userid ? total + Number(post.votes) : total
    }, 0)

    return <div>votes: {tot}</div>;
}

const tot=this.state.posts.reduce((总计,项目)=>item.userid==userid?总计+数量(项目投票数):总计,0)
尝试了这个实现,得到了TypeError:减少没有初始值的空数组更新了我的答案这很有效。我查看了array reduce,发现可选参数初始值设置为0。我们为什么要这样做?为什么它认为数组是空的?使用此实现仍然可以获得5000这很奇怪:这与Callam的实现是相同的,只是它将强制转换为
映射中的数字,而不是
reduce
。常量测试=['1','2','3'].map(i=>Number(i));console.log(test.reduce((a,b)=>a+b,0))//6
const tot = current.map((item) => {
  return Number(item.votes);
})

tot = tot.reduce((a,b)=>a+b,0)