0

我在尝试使用 useQuery() 时收到以下错误。如果您需要更多详细信息,请告诉我。

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一: 1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本相同的应用程序请参阅有关如何调试和解决此问题的提示。

我的代码如下...

获取字符-action.js

import React from "react";
import * as ACTION_TYPES from "./../constants/action-types";
import { useQuery } from "@apollo/react-hooks";
import gql from 'graphql-tag';

export const getCharactersSuccess = (data) => {
    return {
        type:ACTION_TYPES.LOAD_CHARACTERS_SUCCESS,
        data
    }
}

export const getCharactersInProgress = () => {
    return {
        type:ACTION_TYPES.LOAD_CHARACTERS_INPROGRESS
    }
}

export const getCharactersError = (error) => {
    return {
        type:ACTION_TYPES.LOAD_CHARACTERS_ERROR,
        error
    }
}

const GET_CHARACTERS =gql`
{
    allPersons {
        name
        gender
        homeworld {
            name
        }
        species {
            name
            language
            classification
        }
    }
}`;

export const useGetCharacters= () => {
    const { loading, error, data } = useQuery(GET_CHARACTERS);

    if(loading) {
        getCharactersInProgress();
    }

    if(error) {
        getCharactersError(error);
    }

    if(data) {
        getCharactersSuccess(data);
    }
}

上下文状态配置.js

export const ContextState = (props) => {
    // const [stateReducer, dispatchReducer] = useReduceWithLogger(Reducer.AppLoadingReducer,Reducer.initialState);
    const [stateReducer, dispatchReducer] = useReducer(Reducer.MainReducer,Reducer.initialState);

    const handleDispatchAppLoadingInProgress = () => {
        dispatchReducer(GENERIC_ACTION.appLoadingInprogress());
    }

    const handleDispatchAppLoadingSuccess = () => {
        dispatchReducer(GENERIC_ACTION.appLoadingSuccess());
    }

    // const getCharacters = () => {
    //     dispatchReducer(GET_CHARACTERS_ACTION.useGetCharacters());
    // }

    const graphqlClient = new ApolloClient({
        uri: "https://swapi.graph.cool/"
    });

    return (
        <div>
            <ApolloProvider client={graphqlClient}>
                <Context.Provider
                    value={{
                        // reducer
                        isAppReady: stateReducer.isAppReady,
                        dispatchAppLoading: () => handleDispatchAppLoadingInProgress(),
                        dispatchAppLoaded: () => handleDispatchAppLoadingSuccess(),
                        // get character action
                        getCharacters: () => dispatchReducer(GET_CHARACTERS_ACTION.useGetCharacters())
                    }}
                >

                        {
                            props.children
                        }
                </Context.Provider>
            </ApolloProvider>
        </div>
    )
}   
4

1 回答 1

1

您不能GET_CHARACTERS_ACTION.useGetCharacters()在另一个函数内部调用它,就像自定义反应钩子应该只在您的功能反应组件内部调用。

于 2019-12-24T15:33:13.447 回答