[英]React useEffect, how to re render everytime value is updated
I am making like system for my app, and the like system works but the problem is everytime i need to refresh the page to see the updated information..我正在为我的应用程序制作类似的系统,并且类似的系统可以工作,但问题是每次我需要刷新页面以查看更新的信息时..
function Like(props){ var uID = props.uID //sets userId var title = props.name //sets tractk title let userName = props.userName //sets userName let likeCheck; //only true or false const [like, setLike] = useState() useEffect(()=>{ //goes to firebase and check if the value is true or undefined firebase.database().ref("users/"+uID+"/public/"+"songs/"+title+"/widgetInfo/likes/"+userName).on("child_added", (snapshot)=>{ likeCheck = snapshot.val().liked//stores the value in it setLike(likeCheck)//sets the value in it }) }, []) function sendLike (){ //if like is true then it removes the child if (like){ firebase.database().ref("users/"+uID+"/public/"+"songs/"+title+"/widgetInfo/likes/"+userName).remove(); } //if like is undefined, then it adds the child with true value else{ firebase.database().ref("users/"+uID+"/public/"+"songs/"+title+"/widgetInfo/likes/"+userName).push().set({ "userName": userName, "liked": true }) } } return( <div class = "like"> //if like is true then, it shows liked, if false then it shows unliked <i class="material-icons" onClick = {sendLike} >{like? <span>favorite</span>: <span>favorite_border</span> }</i> </div> ) } export default Like
useEffect
?
useEffect
的依赖数组上放一些东西?
You never change the actual value of the like
in the local state of your component.您永远不会更改组件的本地
like
中的实际值。 Try it like this:试试这样:
function sendLike (){
//if like is true then it removes the child
if (like){
setLike(false)
firebase.database().ref("users/"+uID+"/public/"+"songs/"+title+"/widgetInfo/likes/"+userName).remove();
}
//if like is undefined, then it adds the child with true value
else{
setLike(true)
firebase.database().ref("users/"+uID+"/public/"+"songs/"+title+"/widgetInfo/likes/"+userName).push().set({
"userName": userName,
"liked": true
})
}
}
As pilchard said in his comments, you need to use your setLike() hook to change the like state in your sendLike() function.正如 pilchard 在他的评论中所说,您需要使用 setLike() 挂钩来更改 sendLike() function 中的 like state。
Your component will re-render any time the state updates.您的组件将在 state 更新时重新渲染。 Currently with your onClick, you are updating the database, but not updating the component state.
当前使用 onClick,您正在更新数据库,但不更新组件 state。 By updating the component state with your setLike hook you will cause a re-render.
通过使用您的 setLike 钩子更新组件 state 您将导致重新渲染。
Your useEffect() is fine as is.你的 useEffect() 没问题。 It will update the state on initial render (initial render only) based on the database state.
它将根据数据库 state 在初始渲染(仅限初始渲染)时更新 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.