如何在 useEffect() 中进行查询以避免 InvalidHookError?

How do I make a query in useEffect() to avoid InvalidHookError?

我正在尝试查询 api 以在用户登录后获取用户权限。 但是如果我在 useEffect() 中写 useQuery() 就会出现 InvalidHookError 因为它破坏了 React 的 rules of hooks.

const OnHeader = () => {
    const [user, loading, error] =
        typeof window !== "undefined" ? useAuthState(firebase.auth()) : [null, true, null]
    useEffect(() => {
        if (user) {
            user.getIdToken().then(idToken => {
                localStorage.setItem("accessToken", idToken)
            })
            // todo: query permissions and set them in localstorage
            // but if I put useQuery() here it breaks the rules
        }
    }, [user])

}

我目前的解决方法是使用另一个常量 userLoggedIn 来检测用户是否已登录。但我想知道是否有更好的写法?

const OnHeader = () => {
    const [user, loading, error] =
        typeof window !== "undefined" ? useAuthState(firebase.auth()) : [null, true, null]
    const [userLoggedIn, setUserLoggedIn] = useState(false)

    var p = useQuery(
        gql`
            query QueryPermissions {
                permissions {
                    action
                    isPermitted
                }
            }
        `,
        {
            skip: !userLoggedIn,
            onCompleted: data => {
                localStorage.setItem("permissions", JSON.stringify(data))
            },
        }
    )

    useEffect(() => {
        if (user) {
            user.getIdToken().then(idToken => {
                localStorage.setItem("accessToken", idToken)
                setUserLoggedIn(true)
            })
        }
    }, [user])
}

问题不在 useEffect 中,而是在您对 useAuthState 的调用中。您通过有条件地调用挂钩来破坏 the rules of hooks,这是一个禁忌。删除条件调用并将默认值放入自定义挂钩中。