简体   繁体   中英

React useEffect Missing Dependency

React showing missing dependancy, but everything seems ok. I dont want declare function inside useeffect, can you help with that?

Even if I declare all function codes inside usEffect, it tells then user token also missing dependancy. I dont understand what wants react here.. there is no examples in documentation.

const Profile = () => {

    const [user, dispatch] = useContext(UserContext)
    const [login, setLogin] = useState('waiting')
    let [selected, setSelected] = useState('video')
    let [section, setSection] = useState()
    const [userdata,setUserData] = useState()

    useEffect(() => {
        checkCurrentUser()
    }, [])

    let checkCurrentUser = async () => {
        console.log(user.token)
        let result = await requestCurrentUser(user.token)
        if (result.status) {
            await dispatch({
                type: "USER",
                payload: result.data
            })
            setUserData(result.data)
            setLogin('success')
        } else {
            setLogin('failed')
        }
    }

    if (login === 'waiting') {
        return (
            <PianoPlay width={300} classAdd="loading" />
        )
    }
    else if (login === 'failed') {
        return (
            <Redirect push to="/" />

        )
    }

    else if (!userdata.hasOwnProperty('id')) {
        return (
           <Redirect push to="/home" />
        )
    }

You can solve this in two ways.

1 - useEffect(checkCurrentUser, [])

2-

const checkCurrentUser = useCallback(() => {
      ...
    }, [])
    useEffect(() => {
      checkCurrentUser()
    }, [checkCurrentUser])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM