这是我的函数(属于React组件类),它调用了apollo / graphQL突变(doSomething()
)。
example.js
example (id) {
const { elementID, doSomething } = this.props
return doSomething({
variables: { id },
update: (proxy, { data: { getData } }) => {
const data = proxy.readQuery({
query: getDataQuery,
variables: { elementID }
})
// ...do something...
proxy.writeQuery({
query: getDataQuery,
variables: { elementID },
data
})
}
})
}
我需要在单独的文件中获得更新功能,但是现在我失去了elementID
的上下文:
如您所见,当我将update函数放在另一个文件中时,变异调用变得非常可读。但是elementID
不再定义。
example.js
import { update } from './update.js'
example (id) {
const { elementID, doSomething } = this.props
return doSomething({
variables: { id },
update: update
}
update.js
export const update = (proxy, { data: { getData } }) => {
const data = proxy.readQuery({
query: getDataQuery,
variables: { elementID } // <-- not defined
})
// ...do something...
proxy.writeQuery({
query: getDataQuery,
variables: { elementID }, // <-- not defined
data
})
}
答案 0 :(得分:0)
尝试以下操作:
example.js
import { update } from './update.js'
example (id) {
const { elementID, doSomething } = this.props
return doSomething({
variables: { id },
update: update(id, elementID) // <-- change this
}
update.js
export const update = (id, elementID) => { // <-- change this
return (proxy, { data: { getData } }) => { // <-- change this
const data = proxy.readQuery({
query: getDataQuery,
variables: { elementID }
})
// ...do something...
proxy.writeQuery({
query: getDataQuery,
variables: { elementID },
data
})
}
} // <-- change this