【问题标题】:How to use data from readFragment in Apollo?如何在 Apollo 中使用 readFragment 中的数据?
【发布时间】:2018-08-08 01:53:03
【问题描述】:

登录突变后,会返回一个 jwt 令牌和一个用户对象(id 和 firstName)并存储在缓存中(如下图所示)。

我想通过readFragment从缓存中获取用户信息并传递给Layout组件。

所以我尝试在我的布局组件中使用 read Fragment,如下所示:

class Layout extends Component {

  render() {
    const test = this.props.client.readFragment({
      id: 1, // `id` is any id that could be returned by `dataIdFromObject`.
      fragment: gql`
        fragment user on User {
          id
          firstName
        }
      `
    });

    return (
      <div>
        <AppBar
          title="myApp"
        />
        <Sidebar
          //   firstName={this.props.data.firstName}
        />
        {this.props.children}
      </div>
    );
  }
}

export default withApollo(withRouter(Layout));

这里的问题是我不知道如何从 readFragment 结果中传递数据(当我尝试 console.log "test" 结果是未定义的)。 但是当我在片段查询中添加一个不存在的字段时,我收到以下消息:

这个错误是正常的,但证明readFragment可以读取用户信息。

那么如何在我的 Layout 组件中使用 readFragment 中的数据呢?

感谢您的帮助。

编辑: 这是我的 ApolloClient 配置:

const httpLink = createHttpLink({
  uri: "http://127.0.0.1/graphql"
});

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) history.push("/erreur", { errors: graphQLErrors });

  if (networkError) history.push("/erreur", { errors: networkError });
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem("token");
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ""
    }
  };
});

const link = ApolloLink.from([errorLink, authLink, httpLink]);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache({
    dataIdFromObject: object => object.id
  })
});

【问题讨论】:

  • 你能展示你的 Apollo 客户端配置吗?
  • 嗨 magnat,是的,我已经更新了帖子

标签: javascript reactjs apollo react-apollo apollo-client


【解决方案1】:

现在终于可以使用了。我已经更新了我所有的 npm 依赖项,这似乎是问题的根源。 对于那些感兴趣的人,这里是代码:

const data = this.props.client.readFragment({
      id: 1, // `id` is any id that could be returned by `dataIdFromObject`.
      fragment: gql`
        fragment user on User {
          id
          firstName
        }
      `
    });

    if(data)
      console.log(data.id);

这里的缺点是您需要 dataIdFromObject 返回的 id,在我的例子中是用户 id。

如果你想使用你的数据,你只需控制数据变量不为空,然后你就可以使用你需要显示的信息。

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 2020-09-04
    • 2020-07-03
    • 2021-04-04
    • 2022-06-23
    • 2020-02-26
    • 1970-01-01
    • 2021-10-29
    • 2020-10-16
    相关资源
    最近更新 更多