如何使用useMutation或useQuery作为React或React Native上的钩子?

时间:2019-09-23 11:53:30

标签: reactjs react-native react-hooks apollo-client react-apollo-hooks

那是我得到的例外。对我来说这是没有道理的...

无效的挂钩调用。挂钩只能在功能组件的主体内部调用。可能由于以下原因之一而发生: 1.您的React和渲染器版本可能不匹配(例如React DOM) 2.您可能违反了《钩子规则》 3.您可能在同一应用程序中拥有多个React副本 有关如何调试和解决此问题的提示,请参见fb.me/react-invalid-hook-call。

这是我的组件...我正在尝试仅归档标准的登录/密码屏幕...

import React from 'react'
import { View, Text, TouchableWithoutFeedback, TextInput } from 'react- 
native'
import style from './style'
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'
import { faUser, faUnlockAlt } from '@fortawesome/free-solid-svg-icons'
import { Query, useMutation } from 'react-apollo'
import { testQuery, LOGIN_MUTATION } from '../../gql/session'

class LoginForm extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        inProgress: false,
        email: 'hello@hello.com',
        password: '1234'
    }
}
doLogin() {
    const [_doLogin ] = useMutation(LOGIN_MUTATION, {
        update: (proxy, mutationResult) => {
            console.log(mutationResult)
        }
    ,
    variables: {
      $email: this.setState.email,
      $password: this.state.password
    }
    })
     _doLogin()
}
render() {
    return (
        <View style={style.form}>
            <Text style={style.formLabel}>E-Mail</Text>
            <View style={style.formRow}>
                <FontAwesomeIcon size={28} style={style.formIcon} icon={faUser} />
                <TextInput
                    onChangeText={(email) => this.setState({ email })}
                    value={this.state.email}
                    keyboardType={'email-address'}
                    style={style.textInput} />
            </View>
            <Text style={style.formLabel}>Password</Text>
            <View style={style.formRow}>
                <FontAwesomeIcon size={28} style={style.formIcon} icon={faUnlockAlt} />
                <TextInput
                    onChangeText={(password) => this.setState({ password })}
                    value={this.state.password}
                    secureTextEntry={true}
                    style={style.textInput} />
            </View>

            <TouchableWithoutFeedback onPress={() => { this.doLogin() }}>
                <View style={[style.button, style.doLoginButton]}>
                    <Text style={style.buttonText}>Login</Text>
                </View>
            </TouchableWithoutFeedback>
            <View style={style.bellowButton}>
                <TouchableWithoutFeedback onPress={() => this.props.onCancel()}>
                    <Text style={style.cancel}>Cancel</Text>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={() => this.props.onForgot()}>
                    <Text style={style.forgot}>Forgot ?</Text>
                </TouchableWithoutFeedback>
            </View>
        </View>
    )
   }
}


export default LoginForm

那么,怎么了?以及如何存档?

4 个答案:

答案 0 :(得分:2)

您得到的错误是因为您试图在类组件中使用钩子,因此在docs中它们提到了以下内容:

  

您不能在类组件内部使用钩子,但是您可以   绝对将类和函数组件与Hooks混合在一起   树。组件是使用Hooks的类还是函数是   该组件的实现细节。从长远来看,我们   希望Hooks成为人们编写React组件的主要方式。

答案 1 :(得分:0)

我想指出您当前正在使用class component,但是挂钩被设计为与functional component一起使用。因此,一旦您将组件更改为功能组件,就可以按照官方文档中的示例进行如下所示的apollo graphql挂钩,然后针对您的用例进行尝试。

import gql from 'graphql-tag';
import { useMutation } from '@apollo/react-hooks';

const ADD_TODO = gql`
  mutation AddTodo($type: String!) {
    addTodo(type: $type) {
      id
      type
    }
  }
`;

function AddTodo() {
  let input;
  const [addTodo] = useMutation(ADD_TODO);

  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault();
          addTodo({ variables: { type: input.value } });
          input.value = '';
        }}
      >
        <input
          ref={node => {
            input = node;
          }}
        />
        <button type="submit">Add Todo</button>
      </form>
    </div>
  );
}

export default AddTodo();

来源:https://www.apollographql.com/docs/react/essentials/mutations/

答案 2 :(得分:0)

从fb.me/react-invalid-hook-call链接中,错误提示您:

  

只能在函数组件的主体内部调用钩子。

您有一个类组件,需要将其转换为功能组件才能使用react挂钩。

或者,如果您习惯对组件进行分类,请使用Mutation中的'@apollo/react-components'组件。

有关此链接的更多信息:https://www.apollographql.com/docs/react/api/react-components/

答案 3 :(得分:-1)

尝试使用此don froget instll软件包@ apollo / react-hooks

import React from 'react'
import {View, Text, TouchableWithoutFeedback, TextInput} from 'react-
 native '
 import {useMutation} from '@apollo/react-hooks';

import style from './style'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {faUser, faUnlockAlt} from '@fortawesome/free-solid-svg-icons'
import {testQuery, LOGIN_MUTATION} from '../../gql/session'

class LoginForm extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            inProgress: false,
            email: 'hello@hello.com',
            password: '1234'
        }
    }

    render() {
        const [addTodo] = useMutation(ADD_TODO);

        return (
            <View style={style.form}>
                <Text style={style.formLabel}>E-Mail</Text>
                <View style={style.formRow}>
                    <FontAwesomeIcon size={28} style={style.formIcon} icon={faUser}/>
                    <TextInput
                        onChangeText={(email) => this.setState({email})}
                        value={this.state.email}
                        keyboardType={'email-address'}
                        style={style.textInput}/>
                </View>
                <Text style={style.formLabel}>Password</Text>
                <View style={style.formRow}>
                    <FontAwesomeIcon size={28} style={style.formIcon} icon={faUnlockAlt}/>
                    <TextInput
                        onChangeText={(password) => this.setState({password})}
                        value={this.state.password}
                        secureTextEntry={true}
                        style={style.textInput}/>
                </View>

                <TouchableWithoutFeedback
                    onPress={() => {
                      ADD_TODO({
                        variables: {
                            email: this.setState.email,
                            password: this.state.password
                        },
                        update: (proxy, mutationResult) => {
                            console.log(mutationResult)
                        }})}}>


                    <View
                    style={[style.button, style.doLoginButton]}>
                    <Text style={style.buttonText}>Login</Text>
                </View>
            </TouchableWithoutFeedback>
            <View style={style.bellowButton}>
                <TouchableWithoutFeedback onPress={() => this.props.onCancel()}>
                    <Text style={style.cancel}>Cancel</Text>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={() => this.props.onForgot()}>
                    <Text style={style.forgot}>Forgot ?</Text>
                </TouchableWithoutFeedback>
            </View>
        </View>
        ) } }