反应 useEffect 缺少依赖

时间:2021-01-21 15:52:00

标签: reactjs

React 显示缺少依赖关系,但一切似乎都很好。我不想在 useEffect 中声明函数,你能帮忙吗?

即使我在 usEffect 中声明了所有函数代码,它也会告诉用户令牌也缺少依赖项。我不明白这里想要什么反应.. 文档中没有示例。

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

1 个答案:

答案 0 :(得分:0)

您可以通过两种方式解决此问题。

1 - useEffect(checkCurrentUser, [])

2-

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