使用 Apollo Client GraphQL 查询和修改表单

Querying and Mutating a Form with Apollo Client GraphQL

整个 GraphQL 范例对我来说都是新的,通常与 React Redux 一起使用。我的要求是:

  1. 用户单击带有 UID 的行项目

  2. 我们打开一个表格来编辑此数据(预先填充了以前保存的信息)

  3. 然后我们编辑这个数据并保存

我认为 (2) & (3) 将由 <Query><Mutation/><Query> 类型的结构处理,但它不起作用,主要是因为在查询中设置状态将使 textinputs 控制输入.. . 由 <Query> 控制,我无法再对其进行编辑。

除此之外,我还读到 GraphQL 消除了对 Redux 等的需求?所以我不愿意在中间件中粘贴这个查询并传播到 Redux。

有什么想法吗?这应该是一个普遍的要求。其他人想出了什么?

您的数据应作为道具传递给实际呈现表单的任何组件。在该组件的构造函数中,您可以根据道具设置初始状态。一个粗略的例子:

class FormComponent extends React.Component {
  constructor () {
    this.state = this.props.initialState
  }

  render () {
    // Render form using this.state and this.props.update
  }
}

<Mutation mutation={SOME_MUTATION}>
  {(mutate) => (
    <Query query={SOME_QUERY}/>
      {({ data, loading, error }) => {
        if (loading) return <LoadingIndicator/>
        if (error) return <ErrorComponent/>
        if (data) return <FormComponent initialValues={data.someQuery} update={mutate}/>
      }}
    </Query>
  )}
</Mutation>

突变可以进入查询内部,或进入 FormComponent 本身——这一点并不重要。在我们有数据之前我们不会呈现 FormComponent,因此初始值将始终反映查询的结果。