首页 > 解决方案 > 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 中使用?我想这样做的原因是避免在我想要登录用户信息的每个组件中重写此查询。

标签: reactjsgraphqlreact-apollo

解决方案


老实说,对我来说,您似乎只是缺少一个退货声明:

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);

但我没有对其进行测试,也没有采用这种方法 - 试试看,如果它有帮助


推荐阅读