【问题标题】:Setting GraphQL variable dynamically with React Hook is not working使用 React Hook 动态设置 GraphQL 变量不起作用
【发布时间】:2026-02-01 05:35:01
【问题描述】:

我正在使用 useEffect 和 useState 反应钩子在选择更改事件上设置 GraphQL 变量,并根据选择的第一个下拉菜单的哪个选项使用数据填充第二个选择,

所以当我选择选项 A 时,gql 变量应该像这样更新:

{
  variables: {
     selectedOption: "A"
  }
}

但不知何故,未在 useEffect() 上设置 selectOption。在 useEffect 之外,selectOption 受 setSelectOption 影响。

我做错了什么?

我的 GraphQL 查询:

import {gql} from "@apollo/client";

export const GET_SELECT = gql`
query getSelect($selectedOption: String!) {
  categories(where: {name: $selectedOption}) {
    edges {
      node {
        children {
          edges {
            node {
              name
            }
          }
        }
      }
    }
  }
}
`;

我的反应组件

import React, {useState, useEffect} from 'react';
import {useQuery} from "@apollo/client";
import {GET_SELECT} from "./app/queries/get-select";


const FilterBar = ({options}) => {
    const [ selectOption, setSelectOption] = useState('');
    const { data, loading, error } = useQuery(GET_SELECT, {
        variables: {
            selectedOption: selectOption
        }
    });


    useEffect(() => {
        setSelectOption(data?.categories?.edges?.map(first => first?.node?.children?.edges?.map(second => second?.node?.name)));
        console.log('select option' + selectOption);
    }, [data, setSelectOption]);


    if (loading) return "Loading...";
    if (error) return <pre>{( error?.message )}</pre>


    return (
        <>
            <select onChange={(e) => setSelectOption(e.target.value)}>
                <option value="">Select option</option>
                <option value="A">Option A</option>
                <option value="B">Option B</option>
                <option value="C">Option C</option>
            </select>
            <br/>
            <select>
                <option value="">Select data</option>
                {data &&
                    data?.map(opt =>
                        <option value={opt} key={opt}>{opt}</option>
                    )
                }
            </select>
        </>
    )
}


export default FilterBar;

【问题讨论】:

    标签: reactjs variables graphql apollo apollo-client


    【解决方案1】:

    好的,我发现 Graphql 变量“名称”正在返回一个数组,所以我不得不像这样更改查询:

    const GET_SELECT = gql` 
    query getSelect($selectedOption: [String!]) {
      categories(where: {name: $selectedOption}) {
        edges {
          node {
            children {
              edges {
                node {
                  name
                }
              }
            }
          }
        }
      }
    }
    `;
    

    在反应组件中:

    const { data, loading, error } = useQuery(GET_SELECT, {
            variables: { name: [selectOption] },
        });
    

    现在一切正常? 无论如何...感谢@endmaster0809 的帮助!

    【讨论】:

      【解决方案2】:

      请注意setSelectOption 不会立即更新值。 因此,如果您想查看该行之后的更改,请尝试添加 selectOption 作为依赖项或创建仅包含 selectOption 的新 useEffect

      useEffect(() => {
        setSelectOption(data?.categories?.edges?.map(first => first?.node?.children?.edges?.map(second => second?.node?.name)));
        console.log('select option' + selectOption);
      }, [data, setSelectOption, selectOption]);
      

      useEffect(() => {
        console.log('select option' + selectOption);
      }, [selectOption])
      

      对于您的 Graphql 查询,请尝试以下代码。

      export const GET_SELECT = gql`
        query ($selectedOption: String!) {
          getSelect() {
            categories(where: { name: $selectedOption }) {
              edges {
                node {
                  children {
                    edges {
                      node {
                        name
                      }
                    }
                  }
                }
              }
            }
          }
        }
      `;
      

      【讨论】:

      • 感谢您解决了 setSelectOption,但 graphql 变量仍未更新? 第二个“选择选项”未定义。任何想法? @endmaster0809
      • 更新了 GraphQL 变量的描述。
      • 上面的graphql查询抛出语法错误! @endmaster0809