【发布时间】: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