0

我有一个 React Native 表单,我正在尝试将 Formik 与 react-query 一起使用。

问题是在从我收到钩子错误useQuery()调用的函数中使用:onSubmit

警告:从 submitForm() 捕获到未处理的错误 [错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。

我相信我理解错误是什么,但我不明白如何解决这个问题。

我拼凑的例子只是为了演示这个问题:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';
import { useQuery } from 'react-query';
import { Formik } from 'formik';
import axios from 'axios';

const getPokemonList = async () => {
    const { data } = await axios.get("https://pokeapi.co/api/v2/pokemon");
    return data;
};

function authenticate(username, password) {
    const { isLoading, error, data } = useQuery('fetchLuke', getPokemonList);

    if (data) {
        {
            return (
                <Text>
                    {JSON.stringify(data,  null,  2)}
                </Text>
            );
        }
    }

    if (error) {
        return (
            <Text>{error}</Text>
        );
    }

    if ( isLoading ) {
        return (
            <Text>Retrieving Luke Skywalker Information...</Text>
        );
    }
}

export default function App() {

  return (
      <View style={styles.container}>
        <Formik
            initialValues={{ email: '' }}
            onSubmit={(values, actions) => {
                authenticate(values.email);

                actions.resetForm();
            }}
        >
          {({
              handleChange,
              handleBlur,
              handleSubmit, values }) => <View>
            <TextInput
                onChangeText={handleChange('email')}
                onBlur={handleBlur('email')}
                value={values.email}
            />
            <Button onPress={handleSubmit} title="Submit" />
          </View>}
        </Formik>
      </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
4

2 回答 2

0

这是相当简单的。

  1. 创建一个变量并将useQuery赋值给它(在App中,因为useQuery是一个钩子,钩子只能在功能组件中使用)
  2. 在您的 onSubmit 中调用变量或将其传递给身份验证...
于 2022-01-10T10:50:04.780 回答
0

react-query 具有依赖查询功能,其中查询仅在满足自定义条件时运行。

从https://react-query.tanstack.com/guides/dependent-queries检查以下示例

// Get the user
 const { data: user } = useQuery(['user', email], getUserByEmail)
 
 const userId = user?.id
 
 // Then get the user's projects
 const { isIdle, data: projects } = useQuery(
   ['projects', userId],
   getProjectsByUser,
   {
     // The query will not execute until the userId exists
     enabled: !!userId,
   }
 )
 
 // isIdle will be `true` until `enabled` is true and the query begins to fetch.
 // It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :)
于 2020-12-18T10:21:54.657 回答