我正试图创建一个简单的组件,从Apollo GraphQL服务器(查询(返回我的所有组织。我想从上下文状态呈现所有这些组织,在组件安装后(由useEffect钩子处理(,它可以用分派方法放置。
useEffect钩子应调用函数getOrganizations,然后如果状态结果(组织数组(为空,则调用自定义钩子useGetOrganizationsuseGetOrganizationshook使用@apolo/react hook中的useQuery。
不幸的是,这不起作用,我的控制台显示"./src/components/Organisations/Organisations.js第32:13行:React Hook"useGetOrganizations"在函数"getOrganizations"中被调用,该函数既不是React函数组件,也不是自定义的React Hoo克函数React Hook/rules of Hook">
求你了,你能帮我吗?
import React, { useEffect } from 'react';
import { useQuery } from '@apollo/react-hooks';
import ORGANIZATIONS_QUERY from './OrganizationsGraphql';
import { Store } from '../../store/Store';
const Organizations = props => {
const { state, dispatch } = React.useContext(Store);
useEffect(() => {
getOrganizations();
});
const useGetOrganisations = async () => {
const { data, loading, error } = useQuery(ORGANISATIONS_QUERY);
if (loading) {
return 'Loading...';
}
if (error) {
return `Error! ${error.message}`;
}
return dispatch({
type: 'FETCH_ORGANISATIONS',
payload: data.organizations,
});
};
const getOrganizations = () => {
if (state.organizations.length === 0) {
useGetOrganizations();
}
};
return (
<div>
<h1>All organisations</h1>
{console.log(state.organizations)}
</div>
);
};
export default Organizations;
尝试:(使用refetch(
const { data, loading, error, refetch } = useQuery(ORGANISATIONS_QUERY);
const useGetOrganisations = async () => {
if (loading) {
return 'Loading...';
}
if (error) {
return `Error! ${error.message}`;
}
return dispatch({
type: 'FETCH_ORGANISATIONS',
payload: data.organizations,
});
};