创建MutationContainer.js,其中包含您所有的突变导出 MutationContainer 作为变量
import { gql } from 'apollo-boost'
import { adopt } from 'react-adopt'
const mutation1 = () => (
<Mutation mutation={MUTATION1} {...props} />
)
const mutation2 = () => (
<Mutation mutation={MUTATION2} {...props} />
)
const mutation3 = () => (
<Mutation mutation={MUTATION3} {...props} />
)
export const MutationContainer = adopt({
mutation1,
mutation2,
mutation3
})
将它导入到您要使用此突变的任何组件上
在您的 Component1.jsx 上
import { adopt } from 'react-adopt'
import { Value } from 'react-powerplug'
import { MutationContainer } from './MutationContainer'
const Composed = adopt({
input: <Value initial="" />,
container: <MutationContainer />,
})
export const Component1 = () => (
<Composed>
{({ container: { mutation1 }, input }) => {
const handleAdd = ev => {
mutation1.mutation({ variables: { ...variables } })
input.setValue('')
ev.preventDefault()
}
return (
<Form onSubmit={handleAdd}>
<Input
type="text"
value={input.value}
onChange={ev => input.setValue(ev.target.value)}
/>
<Button type="submit">Let's call mutation1</Button>
</Form>
)
}}
</Composed>
)
在 Component2.jsx 上
import { adopt } from 'react-adopt'
import { Value } from 'react-powerplug'
import { MutationContainer } from './MutationContainer'
const Composed = adopt({
input: <Value initial="" />,
container: <MutationContainer />,
})
export const Component2 = () => (
<Composed>
{({ container: { mutation2, mutation3 }, loading }) => {
const handleMutation2 = async () => {
await mutation2.mutation({ variables: { ...variables } })
}
const handleMutation3 = async () => {
await mutation3.mutation({ variables: { ...variables } })
}
return (
<React.Fragment>
<Button onClick={handleMutation2}>
Let's call mutation2
</Button>
<Button onClick={handleMutation3}>
Let's call mutation3
</Button>
<React.Fragment>
)
}}
</Composed>
)
请按照您的要求处理变量
根据你的情况,最重要的一点
export const App = () => (
<MutationContainer>
{({ data: { loading, data } }) => (
<React.Fragment>
<Component1 {...this.props }/>
<Component2 {...this.props } />
</React.Fragment>
)}
</MutationContainer>
)
如果您仍然存在此问题,请告诉我。将尝试使用新方法 react-adopt。