javascript - React useEffect,每次更新值时如何重新渲染
问题描述
我正在为我的应用程序制作类似的系统,并且类似的系统可以工作,但问题是每次我需要刷新页面以查看更新的信息时..
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
吗?
解决方案
like
您永远不会更改组件本地状态中的实际值。试试这样:
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
})
}
}
推荐阅读
- scala - 如何在运行时将 hocon 配置动态加载到案例类中
- recaptcha - Polyfill 会干扰 reCAPTCHA?
- r - 将行作为参数的应用函数应用于 data.table 中的每一行
- java - 存在-Werror时如何将junit5 ExtendWith与模块一起使用
- javascript - Discord.js 嵌入宽度不可靠
- javascript - 单击添加按钮添加另一个带有输入框值的单选按钮
- android - 致命异常:java.lang.IllegalStateException Google Ads
- google-cloud-platform - 在 GCP 脚本中使用最终用户凭据时禁用警告
- python - if else 在带有 for 循环的列表理解中
- python - 检查 HTTP 请求是否在烧瓶中没有参数的最简单方法?