[英]Pass graphQL mutation function as prop or inject it into child component?
我在 reactJS/graphQL-Application 中使用react-apollo
。 有时我确实需要对多个组件进行相同的更改。 那么在调用突变后使用突变和更新数据的最佳方法是什么?
我应该在顶部组件中注入突变并将其传递给所有孩子(示例 2),还是应该在需要的任何地方注入突变(示例 1)?
对于示例 1,在doMutation()
调用后更新现有数据更容易,而传递父组件的doMutation()
函数使更新对我来说更加复杂。
例1(多次进样)
家长
import React, { Component } from 'react'
import { graphql } from 'react-apollo'
import { Button } from 'semantic-ui-react'
import Child from './Child'
import { MUTATION } from 'graphql/'
export class Parent extends Component {
doMutation (event, { name, value }) {
const { someMutation } = this.props
return someMutation({
variables: {
value
}
})
}
render () {
const { data } = this.props
return (
<>
<Button onClick='this.doMutation.bind(this')>Click me to manipulate data</Button>
<Child data={data} />
</>
)
}
}
export default graphql(MUTATION, { name: 'someMutation' })(Parent)
西尔德
import React, { Component } from 'react'
import GrandChild from './GrandChild'
export default class Child extends Component {
render () {
return <GrandChild data={this.props.data} />
}
}
大儿童
import React, { Component } from 'react'
import { graphql } from 'react-apollo'
import { Button } from 'semantic-ui-react'
import { MUTATION } from 'graphql/'
export class GrandChild extends Component {
doMutation (event, { name, value }) {
const { someMutation } = this.props
return someMutation({
variables: {
value
}
})
}
render () {
const { data } = this.props
return (
<Button onClick='this.doMutation.bind(this')>Click me to manipulate data</Button>
)
}
}
export default graphql(MUTATION, { name: 'someMutation' })(GrandChild)
示例 2(将函数作为 prop 传递)
家长
import React, { Component } from 'react'
import { graphql } from 'react-apollo'
import { Button } from 'semantic-ui-react'
import Child from './Child'
import { MUTATION } from 'graphql/'
export class Parent extends Component {
doMutation (event, { name, value }) {
const { someMutation } = this.props
return someMutation({
variables: {
value
}
})
}
render () {
const { data } = this.props
return (
<>
<Button onClick='this.doMutation.bind(this')>Click me to manipulate data</Button>
<Child doMutation={this.doMutation.bind(this)} data={data} />
</>
)
}
}
export default graphql(MUTATION, { name: 'someMutation' })(Parent)
西尔德
import React, { Component } from 'react'
import GrandChild from './GrandChild'
export default class Child extends Component {
render () {
return <GrandChild doMutation={this.props.doMutation} data={this.props.data} />
}
}
大儿童
import React, { Component } from 'react'
import { graphql } from 'react-apollo'
import { Button } from 'semantic-ui-react'
import { MUTATION } from 'graphql/'
export default class GrandChild extends Component {
render () {
const { doMutation } = this.props
return (
<Button onClick='doMutation.bind(this')>Click me to manipulate data</Button>
)
}
}
这主要归结为偏好,但避免将查询结果作为道具传递有一些优点,即:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.