React GraphQl-如何将查询组件的结果返回作为在React上下文中使用的对象



i有一个查询组件,该组件获取已登录的用户的信息。查询本身有效,但是我很难将查询结果作为对象返回,然后想要通过react.createcontext()

我正在使用Apollo客户端在React应用程序中制作我的查询组件。

以下是我当前代码的示例:

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

说实话,对我来说,似乎您只是缺少返回语句:

函数getuser(){ 返回 ( {({加载,错误,data})=> { if(加载)返回加载; 如果(错误)返回错误;

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

但是我没有测试它,也没有采取这种方法 - 请去看看,如果它有帮助

最新更新