Meh*_*ian 0 apollo reactjs graphql apollo-client
我想通过 GrahQL 和 React 保存一个大表单。我将所有表单值都放在一个变量名中:formValue 有没有办法将“formValue”传递给这样的查询?
const [toSaveUserProfile] = useMutation(SAVE_USER_PROFILE)
toSaveUserProfile({ variables: formValue })
const SAVE_USER_PROFILE = gql`
mutation saveUserProfile($profileId: String!) {
updateProfile(profile: { formValue }) {
id
}
}
`
Run Code Online (Sandbox Code Playgroud)
或者我应该一一传递所有字段并像这样定义它们的类型?
const [toSaveUserProfile] = useMutation(SAVE_USER_PROFILE)
toSaveUserProfile({ variables: formValue })
const SAVE_USER_PROFILE = gql`
mutation saveUserProfile($id: String!, $firstName: String, $lastName: String, $age: Int, ......) {
updateProfile(profile: { id: $id, firstName: $firstName, lastName: $lastName, age:$age, ......}) {
id
}
}
`
Run Code Online (Sandbox Code Playgroud)
模式看起来像这样
updateProfile(profile: ProfileDTOInput!): ProfileDTO
type ProfileDTO {
address: String
emails: String
employeeId: String
firstName: String
lastName: String
age: Int
phone: [PhoneDTO]
}
input ProfileDTOInput {
lastName: String
phone: [PhoneDTO]
address: String
age: Int
employeeId: String
emails: String
firstName: String
}
type PhoneDTO {
number: String
phoneType: String
}
input PhoneDTOInput {
phoneType: String
number: String
}
Run Code Online (Sandbox Code Playgroud)
对于此场景,您应该使用 GraphQL 输入类型。为什么?GraphQL 输入类型对于保持参数定义简短而有用,特别是在像您这样的情况下。例如,这个:
mutation saveUserProfile($id: String!, $firstName: String, $lastName: String, $age: Int, ......)
Run Code Online (Sandbox Code Playgroud)
有可能扩展到您定义的突变的无限参数列表。这不仅难以编写,而且也难以维护和阅读。
相反,使用输入类型会大大简化这一过程。
input SaveUserProfileInput {
id: ID!
firstName: String
lastName: String
...
}
mutation saveUserProfile($input: SaveUserProfileInput!) {
updateProfile(input: $input) {
...rest of your code here...
}
}
Run Code Online (Sandbox Code Playgroud)
您的突变现在只需要一个参数——一种输入类型——它是自行定义的。作为架构设计者,您可以在一个位置随意扩展这些字段。您的突变定义及其所需的参数永远不需要更改。
请注意,如果您遵循此方法,则需要更改突变的架构定义updateProfile以接受输入作为类型参数SaveUserProfileInput(或您命名的任何名称)。
有关输入类型的更多信息,我建议查看 Daniel Rearden 的这篇精彩文章:
| 归档时间: |
|
| 查看次数: |
614 次 |
| 最近记录: |