【发布时间】: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