使用 Apollo 客户端 GraphQL 查询和修改表单 [英] Querying and Mutating a Form with Apollo Client GraphQL

查看:51
本文介绍了使用 Apollo 客户端 GraphQL 查询和修改表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The whole GraphQL paradigm is new to me, usually working with React Redux. My requirements are:

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

  1. User clicks a Row Item w/ UID

我们打开一个表单来编辑这些数据(预先填充之前保存的信息)

We open a form to edit this data (with previously saved information pre-populated)

然后我们编辑这些数据并保存

We then edit this data and save

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

I would think (2) & (3) would be handled by a <Query><Mutation/><Query> type of structure but it doesn't work, mainly because setting state in the Query will make the textinputs controlled inputs... controlled by <Query>, and I can no longer edit it.

除此之外,我已经读到 GraphQL 消除了对 Redux 等的需求?所以我不愿意把这个查询放在中间件中并传播到 Redux.

Besides this, I've read that GraphQL removes the need for Redux, etc? So I'm reluctant to go around sticking this query in a middleware and propogating to Redux.

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

Any thoughts? This must be a common requirement. What have others came up with?

推荐答案

你的数据应该作为 prop 传递给实际渲染表单的任何组件.在该组件的构造函数中,您然后根据道具设置初始状态.一个粗略的例子:

Your data should be passed down as a prop to whatever component will actually render the form. Inside that component's constructor, you then set the initial state based on the props. A rough example:

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>

变异可以进入 Query 内部,也可以进入 FormComponent 本身——这一点并不重要.我们在获得数据之前不会渲染 FormComponent,因此初始值将始终反映查询的结果.

The mutation could go inside the Query, or inside the FormComponent itself -- that bit doesn't really matter. We're not rendering the FormComponent until we have data, so the initial values will always reflect the results of the query.

这篇关于使用 Apollo 客户端 GraphQL 查询和修改表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆