【问题标题】:Unable to pass state parameters to mutation无法将状态参数传递给突变
【发布时间】:2018-06-20 19:23:57
【问题描述】:

我阅读了有关Apollo graphql client 的文档,但仍然有一些关于Apolloreact 的问题。

考虑一下,我们有一个简单的表单,其中包含 4 个字段和提交按钮。按下提交后,字段中的值将保存到 this.state.data(仔细检查是否正确保存)。

在后端,我有一个 mutation 之类的:userCreate(input: UserInput): User,它肯定接受此字段输入。

问题是:

如何从this.state.data 字段正确绑定值?

到目前为止,我有以下代码:

onChange = e =>
    this.setState({
      data: { ...this.state.data, [e.target.id]: e.target.value }
    });

  handleSubmit = async () => {
    writeToLog(this.state.data)
    const { name, email, externalId, userCode} = this.state.data
    this.props.userCreateQuery({
      input: {
        name,
        email,
        externalId,
        userCode
      }
    })
  }

这就是突变的样子:

const QUERY_PERSON_MUTATION = gql`
mutation userCreateQuery($name: String!, $email: String!, $externalId: String!, $userCode: String!) {
  userCreate(input: {
    Name: $name,
    Email: $email,
    ExternalId: $externalId,
    UserCode: $userCode}) {
    Name
    Email
    ExternalId
    UserCode
  }
}`;

组件包装:

const NewUserFormWithData = graphql(QUERY_PERSON_MUTATION, { name: 'userCreateQuery' })(NewUserForm);

    export default withApollo(NewUserFormWithData)

更新 1:

架构:

const typeDefs = `
type User {
   UserId: Int
   /* other fields */
}

input UserInput {
   UserId: Int
   UserCode: String
   /* other fields */
}

type Mutation {
   userCreate(input: UserInput): User
   userUpdate(userId: Int, input: UserInput): User    
}`;

【问题讨论】:

    标签: reactjs graphql apollo-client


    【解决方案1】:

    您必须在 variables 键中使用您的数据:

    this.props.userCreateQuery({
      variables: {
          input: {
            name,
            email,
            externalId,
            userCode
          }
      }
    })
    

    PS.:我不知道你的 graphql 服务器,但你可能没有使用你的变异作品的关键输入。

    我们讨论过的呢:

    您的按键输入突变。

     const QUERY_PERSON_MUTATION = gql`
        mutation userCreateQuery($name: String!, $email: String!, $externalId: String!, $userCode: String!) {
          userCreate(
            Name: $name,
            Email: $email,
            ExternalId: $externalId,
            UserCode: $userCode) {
            Name
            Email
            ExternalId
            UserCode
          }
        }`;
    
    this.props.userCreateQuery({
      variables: {
          name,
          email,
          externalId,
          userCode
      }
    })
    

    【讨论】:

    • 这是我尝试的第一件事,但由于某种原因,它失败了。现在也一样。它编译但不执行。
    • 另外,“突变的关键输入”是什么意思?请澄清。
    • “按键输入”对我来说毫无意义,我只是使用你的对象。如果您的 graphql 架构上没有密钥输入,则必须删除突变作品的输入
    • 我明白你想说什么,但这是我能提供的。我只是在玩你的代码仍然没有进展。
    • 您可以编辑您的问题并添加您的 graphql 架构吗?
    猜你喜欢
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 2017-01-26
    • 2023-04-03
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多