【问题标题】:Apollo GraphQL mutations with recompose带有重组的 Apollo GraphQL 突变
【发布时间】:2023-03-05 16:17:01
【问题描述】:

我最近遇到了这个“使用 Apollo 和 Recompose 简化 React 组件”@stubailo https://dev-blog.apollodata.com/simplify-your-react-components-with-apollo-and-recompose-8b9e302dea51

它展示了如何使用 recompose 进行 GraphQL 查询。我想知道是否有人可以提供一个使用 recompose 进行 GraphQL 突变的示例。就像提交表格或类似的东西。

非常感谢。

【问题讨论】:

  • 请问你是怎么做的?

标签: graphql apollo-client recompose


【解决方案1】:

Compose 对突变的使用与查询几乎相同。带有以下表格的简单(未经测试)示例。表单组件有一个文本框并接收一个 submitForm 属性。此属性通过 apollo HoC 包装器映射到 UpdateThing 突变,并传递必要的参数。

Form.jsx

export default class Form extends React.Component {
  state = {
    name: this.props.name
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.submitForm(this.props.id, this.state.name);
  };

  handleChangeName = (e) => {
    this.setState({
      name: e.target.value
    });
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text" id="name" name="name" onChange={this.handleChangeName} value={this.state.name} />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

FormContainer.jsx

const withQuery = ... // Assume query code here

const withUpdateThing = graphql(gql`
  mutation UpdateThing($id: ID!, $name: String!) {
    updateThing(id: $id, name: $name) {
      id
      name
    }
  }
`, {
  props: ({ mutate }) => ({
    submitForm: (id, name) => mutate({ variables: { id, name } })
  })
});

export default compose(withQuery, withUpdateThing)(Form);

然后只需执行&lt;FormContainer id={1} /&gt; 即可使用。 withQuery 注入 name 属性,withUpdateThing 注入 submitForm(id, name) 属性。

【讨论】:

  • 感谢您的回答。但我没有问如何与 Apollo 的 compose 结合使用 GraphQL 突变。我想使用recompose.js 进行突变(提交表单)。我希望我的 Form 是一个纯组件,使用 recompose 的 withState 处理状态和使用 withHandlers 的状态处理程序,并使用 recompose 的 compose 进行撰写。
  • 那么这不是阿波罗客户的问题。我认为这里的例子应该很清楚:github.com/acdlite/recompose
  • @pleuv 我最终暂时使用了您的解决方案,直到我弄清楚重组。非常感谢! :)
  • @YounisShah:你知道了吗?我现在正好站在同一点;-)
猜你喜欢
  • 2019-11-27
  • 1970-01-01
  • 2020-11-11
  • 2020-04-24
  • 1970-01-01
  • 2017-02-07
  • 2021-05-11
  • 2017-08-25
  • 2021-01-08
相关资源
最近更新 更多