我在尝试使用 useQuery(( 时收到以下错误。如果您需要更多详细信息,请告诉我。
错误:挂钩调用无效。钩子只能在身体内部调用 函数组件。以下情况之一可能会发生这种情况 原因: 1. 你可能有不匹配的 React 和渲染器版本(比如 React DOM( 2.你可能违反了钩子的规则 3. 您可能在同一应用程序中有多个 React 副本 有关如何调试和 修复此问题。
我的代码如下...
获取角色操作.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>
)
}
你不能在另一个函数中调用你的GET_CHARACTERS_ACTION.useGetCharacters()
,它就像自定义的反应钩子,应该只在你的函数反应组件中调用。