“比上一次渲染时渲染了更多的钩子"当钩子的初始值是来自数据库的查询结果时出错 [英] "Rendered more hooks than during the previous render" error when the initial value for the hook is a query result from a database

查看:73
本文介绍了“比上一次渲染时渲染了更多的钩子"当钩子的初始值是来自数据库的查询结果时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React 的钩子,并且我想要一个从数据库中检索到的值作为初始值.但是,我收到以下错误:

I'm using React's hook and I want to have a value that is retrieved from the database as the initial value. However, I'm getting the following error:

Invariant Violation:Invariant Violation:渲染的钩子比在上一次渲染期间.

Invariant Violation: Invariant Violation: Rendered more hooks than during the previous render.

const { data, loading, error } = useQuery(GET_DATA)
const { initialValue } = data
const [value, setValue] = useState(initialValue)

我正在使用 React Apollo 钩子.

I'm using the React Apollo hook.

更新

export default NotificationScreen = ({ navigation }) => {
    const { data: initialNotificationSettings, loading: loadingInitialSettings, error: initialSettingsError } = useQuery(GET_NOTIFICATION_SETTINGS)
    if (loadingInitialSettings) {
        return (
            <View style={[styles.container, styles.horizontal]}>
                <ActivityIndicator size="large" color="#FF5D4E" />
            </View>
        )
    }
    if (initialSettingsError) return <Text>Error...</Text>

    const {
        borrowerLendingNotificationToken,
    } = initialNotificationSettings.me
    const [borrowerPending, notifyBorrowerPending] = useState(borrowerLendingNotificationToken)

    return (
        <SafeAreaView style={styles.container}>
        </SafeAreaView>
    )
}

推荐答案

问题是你在 return 下面使用了 hook.尝试更新

The problem is that you are using hook below return. Try to update

export default NotificationScreen = ({ navigation }) => {
    const { data: initialNotificationSettings, loading: loadingInitialSettings, error: initialSettingsError } = useQuery(GET_NOTIFICATION_SETTINGS)

    const [borrowerPending, notifyBorrowerPending] = useState("")

    useEffect(() => {
        if (initialNotificationSettings.me) {
            const { borrowerLendingNotificationToken } = initialNotificationSettings.me
            notifyBorrowerPending(borrowerLendingNotificationToken);
        }
    }, [initialNotificationSettings]);

    if (loadingInitialSettings) {
        return (
            <View style={[styles.container, styles.horizontal]}>
                <ActivityIndicator size="large" color="#FF5D4E" />
            </View>
        )
    }
    if (initialSettingsError) return <Text>Error...</Text>

    return (
        <SafeAreaView style={styles.container}>
        </SafeAreaView>
    )
}

这篇关于“比上一次渲染时渲染了更多的钩子"当钩子的初始值是来自数据库的查询结果时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆