首页 文章

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

提问于
浏览
0

我有一个react-redux应用程序,它使用Apollo客户端对我的api GraphQL进行查询 .

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

这会在我的道具中返回 data ,其中包含:查询响应,如果有错误和加载状态(true或false) .

现在,我正在使用 if(loading) {} 管理自己 .

这个问题是我的组件渲染's in loading state and then again when the query is done loading. If I don'时使用 if(loading) {} ,我得到一个错误,说我需要在查询处于加载状态时返回一些东西 .

有没有办法告诉组件在加载查询时不呈现?

我试过用

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

但那里没有运气 .

有没有办法告诉组件在加载查询时不呈现?

编辑:

这是我的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>
     );
    }
  }
}

1 回答

  • 2

    编辑:问题的海报用这段代码解决了他自己的问题:

    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;
        }
    }
    

    如果数据发生变化,您的函数将返回true并更新 . 你可能会遇到一些边缘情况,所以当事情似乎破裂时不要忘记这个功能

相关问题