首页 文章

重构Apollo GraphQL突变

提问于
浏览
0

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

它显示了如何使用重构进行GraphQL查询 . 我想知道是否有人可以提供一个使用重构进行GraphQL变异的示例 . 就像提交表格或类似的东西一样 .

非常感激 .

1 回答

  • 1

    使用突变进行组合使用与查询几乎相同 . 以下表单的简单(未经测试)示例 . 表单组件有一个文本框并接收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);
    

    然后可以通过简单地执行 <FormContainer id={1} /> 来使用它 . withQuery 注入 name 道具, withUpdateThing 注入 submitForm(id, name) 道具 .

相关问题