【问题标题】:Add +1 to clicked element in array React为数组 React 中的单击元素添加 +1
【发布时间】:2021-06-07 06:53:53
【问题描述】:

我有一个包含一些博客文章的页面,我希望用户能够为每篇文章点赞/点赞,并查看每篇文章有多少赞。

现在,当我喜欢一个帖子时,所有帖子都会获得相同数量的喜欢。我如何只喜欢我点击的帖子?

这是我的代码的相关部分:


    const [posts, setPosts] = useState([])
    let [thumbsNumber, setThumbsNumber] = useState(0)

    const thumbsUp = (x) => {
        console.log('Clicked thumb: ', x)
        setThumbsNumber((thumbsNumber += 1))
    }


return (
        <div>
            {posts.map((post, index) => (
                <div key={index} style={{ marginBottom: '10px' }}>
                
                                <p style={{ float: 'right' }}>{thumbsNumber}</p>
                                <ThumbUpAltIcon
                                    className="thumbsUpBtn"
                                    onClick={() => thumbsUp(post.id)}
                                ></ThumbUpAltIcon>
                </div>
            ))}
        </div>

【问题讨论】:

    标签: javascript arrays reactjs react-hooks


    【解决方案1】:

    thumbsNumber应该是一个对象,设置数字时,应该添加/更新帖子的键(id)。

    注意:如果 thumbsNumber[id] 未定义,我将使用 ?? 0 替换 0。

    const [posts, setPosts] = useState([])
    const [thumbsNumber, setThumbsNumber] = useState({})
    
    const thumbsUp = (id) => {
      console.log('Clicked thumb: ', id)
      setThumbsNumber(thumbs => ({
        ...thumbs,
        [id]: (thumbs[id] ?? 0) + 1
      }))
    }
    
    
    return (
      <div>
        {posts.map((post, index) => (
        <div key={index} style={{ marginBottom: '10px' }}>
          <p style={{ float: 'right' }}>{thumbsNumber[post.id] ?? 0}</p>
          <ThumbUpAltIcon className="thumbsUpBtn" onClick={()=> thumbsUp(post.id)} >
          </ThumbUpAltIcon>
        </div>
        ))}
      </div>
    )
    

    【讨论】:

      【解决方案2】:

      例如,您必须在每个帖子中添加喜欢的编号

      {
        id: 2,
        title: "name",
        ...,
        likes: 1,
      }
      

      然后你必须增加喜欢的数量

      setPosts([...posts, {this field object with new likes number}])
      

      【讨论】:

        【解决方案3】:

        我会在每个帖子中保留它的点赞数。 例如这是帖子:

        {id: 1 ,name: 'post1', data: 'this is post' , numberOfLikes: 0}
        

        然后根据帖子的 id 更新点赞数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-16
          • 2014-06-28
          • 2021-07-19
          • 1970-01-01
          • 2016-07-18
          • 2012-10-16
          相关资源
          最近更新 更多