问题描述
我刚开始使用react-apollo,想知道什么是跨组件共享数据的最佳方法.
I just started using react-apollo and was wondering what was the best way to share data across components.
例如,我有componentA
,它正在使用react-apollo
中的grapql
来获取一些数据(WrappedA
).我的UI中的其他位置也有其他组件componentB
,并且希望使用componentA
已获取的数据.在下面附上一个非常简单的示例.
For example, I have componentA
which is using grapql
from react-apollo
to fetch some data (WrappedA
). I also have some other component, componentB
, somewhere else in my UI and want to use the data already fetched by componentA
.Attached a very simple example below.
const ComponentA = ({ ...props }) => (
<div>
ComponentA...
id: {props.organisationsData.organisations.id}
</div>
)
const ComponentB = ({ ...props }) => (
<div>
****** Want to access props.organisationsData *****
ComponentB...
</div>
)
const organisationsQuery = gql`
query organisations {
organisations {
id
name
}
}
`
const WrappedA = graphql(organisationsQuery, { name: 'organisationsData' })(WrappedA)
const Container = ({ ...props }) => (
<div>
<WrappedA />
<ComponentB />
</div>
)
根据阿波罗文档( https://www.apollographql.com/docs/react/basics/setup.html#in-your-ui ),理想情况下,查询是与UI组件绑定的.
According to the apollo documentation (https://www.apollographql.com/docs/react/basics/setup.html#in-your-ui) ideally the query is tied to the UI component.
我可以用相同的organisationsQuery
包装componentB
,它将使用缓存,但是我无法将查询共定位到我的主要UI部分.我找不到与跨组件共享数据有关的任何信息.
I can wrap componentB
with the same organisationsQuery
and it will use the cache but I wont be able to co-locate my query to my main UI part. I could not find any info related to sharing data across components.
当我尝试
const WrappedB = graphql(gql`
query organisations {
organisations {
id
}
}
`, { name: 'organisationsData' })(WrappedB)
(省去了name
)我看到了对graphql端点的额外调用.这不理想.
(leaving out name
) I saw an extra call made to the graphql endpoint.This is not ideal.
访问已从服务器获取的数据的最佳方法是什么? (使用v2,因此无法使用现有的Redux存储,手动访问缓存似乎很底层,并且该用例在网站上未提及: https://www.apollographql.com/docs/react/basics/caching.html )
What would be the best way to access data already fetched from the server? (using v2 so cannot use an existing redux store, accessing the cache manually seems low level and this use case is not mentioned on the site: https://www.apollographql.com/docs/react/basics/caching.html)
谢谢.
推荐答案
您可以使用apollo链接,这是本地状态管理,您可以阅读文档
you can use apollo link , this is local state management , you can read documentation
apollo-link-state允许您将本地数据与远程数据一起存储在Apollo缓存中.要访问您的本地数据,只需使用GraphQL查询它.您甚至可以在同一查询中请求本地和服务器数据!
apollo-link-state allows you to store your local data inside the Apollo cache alongside your remote data. To access your local data, just query it with GraphQL. You can even request local and server data within the same query!
https://www.apollographql.com/docs/react/essentials/local-state.html
这篇关于Apollo GraphQL(React)组件之间的数据共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!