当 Apollo 查询为 'loading' 时不呈现 - React

Not render when Apollo query is 'loading' - React

我有一个使用 Apollo 客户端查询我的 api GraphQL 的 react-redux 应用程序。

我有一个 GridContainer 使用 export default connect(mapStateToProps, mapDispatchToProps)(GridContainerWithData); 进行查询调用,其中 GridContainerWithData 是一个 const 使用 graphql(gql`...)

进行查询

这个 returns data 在我的道具中包含:查询响应,如果有错误和加载状态(真或假)。

现在,我正在使用 if(loading) {} 自行管理加载。

这里的问题是我的组件在加载状态时呈现,然后在查询完成加载时再次呈现。如果我不使用 if(loading) {},当查询处于加载状态时,我会收到一条错误消息,提示我需要 return。

有什么方法可以告诉组件在查询 loading 时不呈现?

我试过使用

shouldComponentUpdate (nextProps) {
    if (this.props.data.loading !== nextProps.data.loading) {
      console.log(‘i will rerender’, nextProps.data.loading);
      return true;
    }else {
      return false;
    }
}

但运气不好。

有什么方法可以告诉组件在查询 loading 时不呈现?

编辑:

如果它可以帮助任何人,这就是我的 GridContainer。

class ActionsToDoGridContainer extends Component {

 render () {
   const {error} = this.props.data;

   if (error) {
     return (
       <div className='ComponentDistance'>
         An unexpected error happened :
         {error}
       </div>);
    } else {
     return (
        <div className='ComponentDistance'>
          <ActionsToDoGrid {...this.props}/>
         ActionsToDoButtons {...this.props}/>
        </div>
     );
    }
  }
}

编辑:发帖人用这段代码解决了他自己的问题:

shouldComponentUpdate(nextProps) { 
  if (nextProps.data.loading === false) { 
    return true;
  } else {
    return false;
  }
}

我认为您 shouldComponentUpdate 的思考方向是正确的,但与其检查加载状态是否不同,不如检查您的数据是否不同。

shouldComponentUpdate (nextProps) {
    const thisData = this.props.data.queryDataResponse;
    const nextData = nextProps.data.queryDataResponse;
    if (!someLibrary.deepEquals(thisData, nextData)) {
      return true;
    }else {
      return false;
    }
}

如果数据发生变化,您的函数将 return 为真并更新。您可能会 运行 遇到一些边缘情况,所以当事情似乎中断时不要忘记此功能