javascript - React HOC 查询 graphql
问题描述
我需要在我的应用程序的多个页面中查询 graphql,并且我正在尝试创建一个反应高阶函数来执行此操作。
这是原文:
const Profiles = () => {
// Omitted code
const { loading, error, data, refetch, fetchMore } = useQuery(
GET_PROFILES(),
{
variables: { id },
}
);
if (loading) {
return <Loading />;
}
if (error) {
// I need to find a way to eliminate this line because I am duplicating it on every page of my app
if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
return <Redirect to="/login" />;
}
return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
}
return (
<div>OMITTED</div>
);
};
这就是我目前拥有的:
const WithQuery = (Comp, query, getVariables) => (props) => {
const { loading, error, data, refetch, fetchMore } = useQuery(
query(),
{
variables: getVariables(),
}
)
if (loading) {
return <Loading />;
}
if (error) {
// I need to find a way to eliminate this line because I am duplicating it on every page of my app
if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
return <Redirect to="/login" />;
}
return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
}
return <Comp {...props} />
}
const Profiles = WithQuery(() => {
return (
const {id} - useContext(UserContext);
<div>OMITTED</div>
);
}, GET_PROFILES, () => ({ id }));
}, GET_PROFILES, () => ({ id }));
由于找不到此行 ID,我收到错误消息。如何向 hoc 发送 id 道具,以及如何从要显示的 div 内部的查询中访问数据?
解决方案
id
未定义,因为它仅存在于您的匿名函数组件的上下文中( . 它的第一个参数WithQuery
。它只能在定义它的函数内部使用。
您实际上可以在getVariables()
函数中使用钩子,因此应该可以通过将const {id} = useContext(UserContext)
行移到() => ({ id })
函数中来修复它。
推荐阅读
- .net - 门户中的 Azure 应用服务应用设置不会覆盖 appsettings.json 值
- python-3.x - Python - 迭代 while 循环以编译程序的平均运行时间
- vb.net - 按字符编号排序多行文本框
- powershell - 跨多个项目加速 Out-File
- c# - 与多个环境共享单个 AmazonMQ?
- azure - 无法通过提供的链接访问暂存部署槽中的 Azure Web App
- javascript - 如何使用 PHP GET 请求打开 Bootstrap 模式?
- python - 请求无法正常工作的 Web 抓取
- bluehost - 在 bluehost 上安装 python 3
- google-closure - 如何在 Google Closure 编辑器上对按钮进行分组?