当钩子的初始值是来自数据库的查询结果时,“渲染的钩子比上一次渲染时更多”错误

IT技术 reactjs react-native react-hooks react-apollo
2021-05-09 07:26:34

我正在使用 React 的钩子,我希望有一个从数据库中检索到的值作为初始值。但是,我收到以下错误:

Invariant Violation:Invariant Violation:比上一次渲染时渲染了更多的钩子。

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

我正在使用 React Apollo 钩子。

更新

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>
    )
}
1个回答

问题是您在返回下方使用钩子。尝试更新

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