如何在Apollo查询渲染道具中调用setState?

时间:2018-08-19 07:02:13

标签: reactjs graphql apollo react-apollo

我试图结合使用setState和Apollo Query在顶级组件上创建错误。我实际上是在使用React Context,但这有共同点。

setError = () => this.setState({ isError: true });

render() {
  return (
   this.state.isError ? <CustomError /> : (
   <Query>
     {({ loading, error, data }) => {

       // first error check
       if (error) { 
         this.setError();
         // this all works if I return <div /> right here, but that's kinda bad
       }
       // I also want to set an error in a child component
       <VeryComplicatedComponentThatCantBeInThisFile setError={this.setError}>
     })
   </Query>
   )
  );
}

有人知道如何最好地做到这一点吗?

1 个答案:

答案 0 :(得分:0)

在使用渲染道具缓存表单数据时,我遇到了类似的问题。幸运的是,它提供了onErroronComplete回调,以便您可以在那里设置状态。请注意,使用缓存时不会触发这些回调。

class MyComponent extends React.Component {
  setError = () => this.setState({ isError: true });
  handleQueryError = error => {
    this.setError();
  };
  handleQueryComplete = data => {
    this.setState({formData: data});    
  };
  render() {
    return (<Query 
      fetchPolicy="network-only"
      onError={this.handleQueryError}
      onComplete={this.handleQueryComplete}>
      {({ loading, error, data }) => {
        return <VeryComplicatedComponentThatCantBeInThisFile isError={this.state.isError}>
      }}
    </Query>);
  }
}
相关问题