[英]React HOC query graphql
我需要在我的应用程序的多个页面中查询 graphql 并且我正在尝试创建一个反应更高阶的 function 来执行此操作。
这是原文:
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
未定义,因为它仅存在于您的匿名 function 组件的上下文中( WithQuery
的第一个参数。它只能在定义它的 function 内部使用。
您实际上可以在getVariables()
function 中使用钩子,因此应该可以通过将const {id} = useContext(UserContext)
行移动到() => ({ id })
function 来修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.