【发布时间】:2019-04-26 02:25:36
【问题描述】:
使用 apollo 和 react,我想根据(远程)apollo 查询的结果更新我的本地 apollo 状态。
查询的类型为[String!]!,我的本地状态包含String 类型的{name}。我想将本地 { name } 分配给查询返回的第一项。
const App = compose(
graphql(gql`{ name @client }`, { name: 'localData' }),
graphql(gql`{ currencies { name } }`)
)(({ localData }) => <h1>{ localData.name }</h1>)
我不想使用 componentWillReceiveProps(一旦 props 来自远程查询,就在那里改变本地状态),因为这是不好的做法。
我需要使用本地 apollo 状态,而不仅仅是组件的状态,因为这个值将被其他组件使用。
我尝试使用 graphql hoc 的 props 配置,但感觉和 componentWillReceiveProps 一样糟糕,并导致无限循环。
有什么想法吗?
相关版本:
"apollo-boost": "^0.1.19",
"apollo-link-state": "^0.4.2",
"react-apollo": "^2.2.4",
代码
import React from 'react'
import ReactDOM from 'react-dom'
import ApolloClient from 'apollo-boost'
import gql from 'graphql-tag'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloProvider, graphql, compose } from 'react-apollo'
import { ApolloLink } from 'apollo-link'
import { withClientState } from 'apollo-link-state'
import { HttpLink } from 'apollo-link-http'
const resolvers = {
Mutation: {
updateName: (ops, { name }, { cache }) => cache.writeData({ data: { name } })
}
}
const typedefs = gql`
type Query {
name: String
}
type Mutation {
updateName(name: String): String
}
`
const defaults = { name: 'defaultName' }
const cache = new InMemoryCache()
const stateLink = withClientState({
cache,
defaults,
resolvers
});
const apolloClient = new ApolloClient({
uri: '/store/api/graphql',
link: ApolloLink.from([stateLink, new HttpLink()]),
cache,
clientState: {
defaults,
resolvers,
typedefs
}
})
const App = compose(
graphql(gql`{ name @client }`, { name: 'localData' }),
graphql(gql`{ currencies { name id } }`)
)(({ localData }) => <h1>{ localData.name }</h1>)
ReactDOM.render(
<ApolloProvider client={ apolloClient }>
<App />
</ApolloProvider>,
document.getElementById('app')
)
【问题讨论】:
标签: graphql apollo react-apollo apollo-client