【发布时间】:2021-09-12 18:06:20
【问题描述】:
我的目标是在更改 Select 选项后使用自定义挂钩从 API 获取数据。
我在 Select-field 上有一个 onChange 事件,如下所示:
<Select options={customers.customers} onChange={updateMarkers} />
被调用的函数updateMarkers如下所示:
const updateMarkers = (selectedOption) => {
const warehouses = GQLQuery(`
{
warehouses(where: {customer: {id: "${selectedOption.value}"}}) {
name
address {
city
lat
lng
road
zipcode
housenumber
province {
name
}
country {
name
}
}
}
}
`)
console.log(warehouses)
}
在这个函数中,我调用了一个自定义钩子 (GQLQuery),它获取如下所示的数据(如果我不是从事件中调用它,它会起作用):
import { gql, useQuery } from "@apollo/client";
function GQLQuery(query) {
const { loading, error, data } = useQuery(gql`${query}`);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
if (data) return data
}
选择一个选项后我得到的错误是:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
很明显,我违反了 Hooks 规则,因为我刚开始使用 React,并且缺少很多基础知识,但我无法理解我在这里做错了什么。有人可以指出我需要了解的文档或指向我的解决方案。谢谢!
【问题讨论】:
-
如果需要任何额外信息,请告诉我!
标签: reactjs graphql react-hooks apollo-client