reactjs - React GraphQL - 如何将查询组件的结果作为对象返回以在 React 上下文中使用
问题描述
我有一个查询组件,它获取已登录用户的信息。查询本身有效,但我无法将查询结果作为对象返回,然后我想将其传递给 React.createContext()
我正在使用 Apollo 客户端在我的 React 应用程序中创建我的 Query 组件。
以下是我当前代码的示例:
function getUser() {
return (
<Query query={query.USER_INFO}>
{({ loading, error, data }) => {
if (loading) return <div>Loading</div>;
if (error) return <div>error</div>;
const userInfo = {
name: data.user.name,
age: data.user.age,
}
}}
</Query>
);
}
//need userInfo object to go here
export const UserContext = React.createContext(userInfo);
如何获得查询的返回然后在 React.createContext 中使用?我想这样做的原因是避免在我想要登录用户信息的每个组件中重写此查询。
解决方案
老实说,对我来说,您似乎只是缺少一个退货声明:
function getUser() { return ( {({ loading, error, data }) => { if (loading) return Loading; if (error) return error;
const userInfo = {
name: data.user.name,
age: data.user.age,
}
return userInfo // ----- this here
}}
</Query>
);
}
//need userInfo object to go here
export const UserContext = React.createContext(userInfo);
但我没有对其进行测试,也没有采用这种方法 - 试试看,如果它有帮助
推荐阅读
- ios - 如何在 iOS 的 AV 播放器中设置自定义标题
- javascript - 如何根据其他循环中的变量创建定时循环?
- python - 使用 Python Selenium 下载文件
- angular - 在 Angular/Typescipt 中,通用调用和 .. as Casting 之间有什么区别?特别是对于 HttpClient
- python - 如何打印“\”并避免代码拆分?
- sql - 与字段的时差
- html - 如何使 fullcalendar4 中的可拖动事件区域可滚动?
- c - 从函数返回结构给我分段错误
- javascript - 我无法从我的 Google Play 商店控制台获取订阅 ID,导致找不到错误项目
- html - 看起来我的媒体查询没有改变我的字体大小