【问题标题】:How to combine React hooks (useContext, useEffect) with Apollo react hooks (useQuery)如何将 React 钩子(useContext、useEffect)与 Apollo 反应钩子(useQuery)结合起来
【发布时间】:2020-02-20 23:24:12
【问题描述】:

我正在尝试创建一个简单的组件,该组件从 Apollo GraphQL 服务器(查询)返回我的所有组织。我想从上下文状态渲染所有这些组织,在该上下文状态中,可以在组件安装后使用调度方法放置它(由 useEffect 钩子处理)。

useEffect 钩子应该调用函数 getOrganizations,然后如果状态结果(组织数组)为空,则调用自定义钩子 useGetOrganizationsuseGetOrganisations 钩子使用来自 @apollo/react-hooks 的 useQuery

不幸的是,这不起作用,我的控制台显示“./src/components/Organisations/Organisations.js 第 32:13 行:React Hook "useGetOrganisations" 在函数 "getOrganisations" 中被调用,该函数既不是 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;

【问题讨论】:

标签: reactjs react-hooks react-context


【解决方案1】:

尝试:(使用重新获取)

    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,
        });
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2020-05-02
    • 2021-05-31
    • 2021-03-02
    • 2020-11-15
    • 2019-10-07
    • 2019-09-14
    相关资源
    最近更新 更多