[英]Issue to show a like counter in the front end in React JS (but it works in the API)
我第一次在这里发帖!
我们正在处理一个小组项目,我们在前端增加一个项目时遇到问题。 目前我们可以在我们的 console.log 中检查点击按钮时数字正在上升。
尽管如此,我们必须刷新页面才能看到新的“赞”。
所以这是我们组件中的代码。
import "./Post.css";
import { useEffect, useState } from "react";
import { addLike, createPost } from '../../lib/social-network-library-master';
function Post({post}) {
const handleLikes = async () => {
let result = await addLike(post._id)
};
return (
<div id="general-container">
<h2>{post.title}</h2><br/>
<p>{post.content}</p><br/>
<p>Posté par {post.firstname} {post.lastname}</p><br/>
<div className="boutton-like-container">
<button className="boutton-like" onClick={() =>handleLikes()}>
like
</button>
<p>{post.likes.length} likes</p>
</div>
</div>
)
};
export default Post;
这里需要一个state来管理点赞。
就像是
const [counter, setCounter] = useState(0)
const handleLikes = async () => {
let result = await addLike(post._id);
//setCounter(prev => prev + 1);
// if the result is coming from api then instead just set the response that you get
setCounter(result)
};
然后在用户界面中你可以像这样渲染它
<p>{counter}</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.