gpt4 book ai didi

relayjs - 将变量传递给现代中继中的片段容器

转载 作者:行者123 更新时间:2023-12-02 11:41:24 27 4
gpt4 key购买 nike

我正在使用Relay Modern (兼容)。我有一个片段,其中包含一个具有一个参数的字段,但我找不到一种从父组件传递变量值的方法:

// MyFragmentComponent.jsx

class MyFragmentComponent extends Component {...}

const fragments = {
employee: graphql`
fragment MyFragmentComponent_employee on Employee {
hoursWorked(includeOvertime: $includeOvertime)
dob
fullName
id
}
`,
}

export default Relay.createFragmentContainer(MyFragmentComponent, fragments)

最终会显示 $includeOvertime 未定义。渲染该组件的上下文如下所示:

// MyRootComponent.jsx

class MyRootComponent extends Component {
render() {
const { employee } = this.props
const includeOvertime = //... value is available here

return (
<div>
<MyFragmentComponent employee={employee} />
</div>
)
}
}

const query = graphql`
query MyRootComponentQuery($employeeId: String!) {
employee(id: $employeeId) {
fullName
...MyFragmentComponent_employee
}
}
`

export default MyUtils.createQueryRenderer(MyRootComponent, query) // this just returns a QueryRenderer

使用经典中继,您可以这样传递变量:

....
employee(id: $employeeId) {
fullName
${MyFragmentComponent.getFragment('employee', variables)}
}

如何使用现代继电器实现相同的目标?

最佳答案

使用@argumentDefinitions@arguments指令似乎是正确的方法。在 1.4.0 之前的中继版本中,必须使用 graphql.experimental 而不是 graphql

在片段定义中:

const fragments = {
employee: graphql`
fragment MyFragmentComponent_employee on Employee
@argumentDefinitions(includeOvertime: { type: "Boolean", defaultValue: false }) {
hoursWorked(includeOvertime: $includeOvertime)
dob
fullName
id
}
`,
}

如果您希望参数为必需:

@argumentDefinitions(includeOvertime: { type: "Boolean!" })

在父组件中,您应该像这样指定片段的参数:

const query = graphql`
query MyRootComponentQuery($employeeId: String!, $includeOvertime: Boolean) {
employee(id: $employeeId) {
fullName
...MyFragmentComponent_employee @arguments(includeOvertime: $includeOvertime)
}
}
`

this page在官方中继文档中有一个用于定义/传递参数的指令示例。

更新:

Since relay version 1.4.0 graphql.experimental was deprecated and now all the features are supported by the regular graphql tag.

更新:

In relay version 1.5.0 graphql.experimental was removed.

关于relayjs - 将变量传递给现代中继中的片段容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44753480/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com