我正在尝试创建一个简单的组件,该组件将从Apollo GraphQL服务器(查询)返回我的所有组织。我想从挂载组件后可以通过调度方法放置的上下文状态(通过 useEffect 钩子处理)呈现所有这些组织。
如果状态结果(组织数组)为空,则useEffect 挂钩应调用函数 getOrganizations ,然后调用自定义挂钩 useGetOrganizations 。 useGetOrganisations 挂钩使用@ apollo / react-hooks中的 useQuery 。
不幸的是,这不起作用,我的控制台显示“ ./src/components/Organisations/Organisations.js 32:13行:在函数“ getOrganisations”中调用了React Hook“ useGetOrganisations”,该函数既不是React函数组件也不是自定义的React Hook函数react-hooks / rules-of-hooks”
请,你能帮我吗?
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;
答案 0 :(得分:0)
尝试:(使用重新获取)
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,
});
};