首页 > 解决方案 > 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吗?

标签: javascriptreactjsfirebasefirebase-realtime-databaserxjs

解决方案


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
        })
    }
}

推荐阅读