【问题标题】:How to increment a value using onClick in react如何在反应中使用 onClick 增加值
【发布时间】:2021-12-04 15:21:18
【问题描述】:

我有一个按钮,当按下 onClick 触发器 LikeComment 时,它会使用当前评论 ID 和发布评论的用户将赞发布到数据库。

    <button className="btn" onClick={LikeComment(comment_id, user_id)}>
      <div className="text">
        <i className="fas fa-thumbs-up"></i>
        <p>{comment_likes.length}</p>
      </div>
    </button>

按下按钮时增加comment_likes.length 的最佳方法是什么。现在我的问题是该值仅在页面刷新时更新。

我尝试过这样做,但它没有按预期工作

<p>{comment_likes.length && LikeComment ? (comment_likes.length+1) : (comment_likes.length)}</p>

我想通过检测何时按下 LikeComment 以将原始值增加 1 来实现这一点。

任何解决此问题的提示将不胜感激..

【问题讨论】:

  • 您可以更新本地状态,或触发重新获取更新的数据库数据。您能否更新您的问题以包含包含所有相关代码的minimal, complete, and reproducible code example
  • useState 挂钩将提供一个变量和一个设置其值的函数。 reactjs.org/docs/hooks-state.html 你可以在你渲染的 JSX 中包含这个变量,它会在值更新时更新。我建议您也尝试一个介绍性的反应教程,这是相当基本的反应。 reactjs.org/docs/getting-started.html#learn-react
  • @nlta 我已经尝试过 useState 但我得到了一个 Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. 因为该按钮包含在地图函数中以显示 cmets。
  • 发布该组件的所有代码。你还有其他错误。
  • comment_likes 来自哪里?您的问题中没有足够的信息来帮助您。

标签: javascript reactjs conditional-operator


【解决方案1】:

首先,您需要将当前的like数量存储在组件的本地状态中。这样你就可以只显示当前的点赞数量,如果你更改buttonLikes 数量,react 会自动更新显示。

const [buttonLikes, setButtonLikes] = useState(comment_likes)

然后你需要一个事件处理程序,它会增加类似的数量并将你的更改发布到数据库


    const handleClickLikeButton = (comment_id, user_id) => {
        setButtonLikes((prevValue) => prevValue + 1)
        LikeComment(comment_id, user_id)
    }

现在您的显示逻辑将如下所示

   <button className="btn" onClick={handleButtonLike(comment_id, user_id)}>
      <div className="text">
        <i className="fas fa-thumbs-up"></i>
        <p>{buttonLikes}</p>
      </div>
    </button>

【讨论】:

  • 这对我有帮助,谢谢! setButtonLikes((prevValue) =&gt; prevValue + 1) 工作。
【解决方案2】:

你可以使用

const [likesCount, setlikesCount] = useState(0)

然后创建一个这样的函数:

 const callapiforlike=(comment_id, user_id){
   // call some api
  }
 const handleLikeCountIncrement= (comment_id, user_id) => {
        setlikesCount(likesCount + 1)
        callapiforlike(comment_id, user_id)

    }

点赞按钮

<button className="btn" onClick={handleLikeCountIncrement(comment_id, user_id)}>
      <div className="text">
        <i className="fas fa-thumbs-up"></i>
        <p>{likesCount}</p>
      </div>
    </button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多