与阿波罗的Redux-Form

时间:2017-11-02 22:50:07

标签: reactjs redux redux-form apollo react-apollo

我正在尝试查找与Apollo一起使用的Redux-Form的示例,但找不到任何内容。我有一个现有的Redux-Form组件,我想触发使用我的GraphQL变异提交。那怎么样?

1 个答案:

答案 0 :(得分:1)

我不确定你是否还需要它,但这是一个可能的解决方案。也许不是最好的组件组合,但这个简单的例子可以帮助你或其他人用redux-form和apollo创建自己的表单。

在最简单的场景中,我们可以将所有内容放在一个组件中。下面是一段代码:

import React from 'react'
import { graphql, compose } from 'react-apollo' 
import { Field, reduxForm } from 'redux-form'
import { submitForm } from './somewhere' //you can also define mutation in this file

class ApolloForm extends React.Component {
  submitForm = (data) => {
    return this.props.submitForm({
      variables: {firstName: data.firstName, lastName: data.lastName}
    })
  }

  render() {
    const { handleSubmit, submitting, submitSucceeded } = this.props
    return (
      <form onSubmit={handleSubmit(this.submitForm)}>
        <Field
          name="firstName"
          component="input"
          type="text"
        />
        <Field
          name="lastName"
          component="input"
          type="text"
        />
        <button type="submit" disabled={submitting}>Submit</button>
        { submitSucceeded && <p>Sent!!!</p> }
      </form>
    )
  }
}

const ApolloForm = compose(
  graphql(submitForm, {name: 'submitForm'},
  reduxForm({form: 'ApolloForm'})
)(ApolloForm)