在React上构建喜欢的帖子功能

时间:2018-06-29 04:17:58

标签: javascript arrays reactjs

我正在尝试为项目管理网站构建喜欢的帖子(任务/评论)。 我当前的逻辑是,使用用户ID,任务ID和一个布尔taskLiked变量来存储是否喜欢某个任务。

到目前为止,这就是我所拥有的

this.state = {

taskLikeInfo: [],
 //an array containing taskId, userId, taskLiked boolean for each user who likes/unlikes a post
}

类似按钮的事件处理程序

handleClick(event) {

        var tasks = this.state.taskLikeInfo;
        const result = tasks.filter(task => ((task.taskId==this.props.activeTask)&&(task.userId==this.props.user.id)));
        console.log('tasks,result:', tasks, result)
        if (result.taskLiked===true)
        {
            this.unlikeTask(event)

        }
        else  {
            this.likeTask(event)

        }
    }

like函数

likeTask(){

  var taskId = this.props.activeTask;
  var userId = this.props.user.id;
  var tasks = this.state.taskLikeInfo;
  tasks.push({ taskId, userId, taskLiked:true })
  var destArray = _.uniq(tasks, function(x){
    return x.taskId;
  });
  this.setState({taskLikeInfo : tasks})
}

与众不同的功能

unlikeTask(){

  var taskId = this.props.activeTask;
  var userId = this.props.user.id;
  var tasks = this.state.taskLikeInfo;
  this.props.unlikeTask(taskId,userId)
  // _.uniq takes a json array and eliminates all repeating elements so that the final array can be used to count total unique likes on a post
  var destArray = _.uniq(tasks, function(x){
    return x.taskLiked;
  });
  destArray.map((task, index) => {
    if((task.taskId==taskId)&& (task.userId==userId) && (task.taskLiked===true)){
      //the user is clicking on an already liked comment which should toggle it
      task.taskLiked=false;

    }
  })

  this.setState({taskLikeInfo: destArray})
}

render()函数

<div className="like-task">
  <a class="btn btn-sm" onClick={this.handleClick} data-taskid={this.props.activeTask} >    
    { this.state.taskLikeInfo.map((task, index) => {
      return (
        <i className={"fa fa-" + ( task.taskLiked ? 'heart-o' : 'heart')} > </i>
      );
    }) }  
    Like
  </a>
</div> 
  1. 如果喜欢/不喜欢相同的评论,那么它会起作用

  2. 如果喜欢评论A,那么喜欢评论B,然后先对评论A进行修改,然后再喜欢评论B(在同一单击中)

有人可以修复我当前的代码,或建议其他更清洁的解决方法。谢谢。 Codepen演示.. https://codepen.io/rafay-shahid/pen/dKwagV?editors=1011

1 个答案:

答案 0 :(得分:0)

我认为您可以重构它以使逻辑更简单,并解决您具体描述的问题。

渲染喜欢的按钮时-您希望将taskID与handleClick一起传递。

onClick={this.handleClick(this.props.activeTask)}

在您的onClickHandler内:

handleClick(event, taskId) {
  //if task is currently liked by user
  //unlike it
  //else like it
  //update state with new likes
}

我会编写代码,但是如果没有数据结构的示例,这很困难。

相关问题