阿波罗GraphQL突变的重新合成

阿波罗GraphQL突变的重新合成

问题描述:

我最近遇到了这个“简化您的反应的组分与阿波罗和重新构图” @stubailo https://dev-blog.apollodata.com/simplify-your-react-components-with-apollo-and-recompose-8b9e302dea51阿波罗GraphQL突变的重新合成

它表明你如何能做到GraphQL查询与重新合成。我想知道是否有人可以提供一个用重构来做GraphQL变种的例子。就像提交表单或类似的东西一样。

非常感谢。

+0

我可以问你如何做到这一点? –

使用突变编写使用与查询几乎相同。简单的(未经测试的)例如下面的表格。表单组件有一个文本框并接收一个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)道具。

+0

感谢您的回答。但是我没有问及如何将GraphQL突变与Apollo的“撰写”结合在一起。我想用'recompose.js'做一个变异(一个表单提交)。我希望我的'Form'是一个纯组件,用'withState'处理状态,用'withHandlers'处理状态处理器,并使用重构的'compose'组合。 –

+0

然后,这不是一个apollo客户端问题。我认为这里的例子应该是非常清楚的:https://github.com/acdlite/recompose – pleunv

+0

@pleuv我结束了使用你的解决方案的时间,直到我找出重组。非常感谢! :) –