【问题标题】:Not render when Apollo query is 'loading' - React当 Apollo 查询“加载”时不呈现 - React
【发布时间】:2017-11-15 11:46:00
【问题描述】:

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

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

这会在我的 props 中返回 data,其中包含:查询响应、是否有错误以及加载状态(true 或 false)。

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

这里的问题是我的组件在它处于加载状态时呈现,然后在查询完成加载时再次呈现。如果我不使用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>
     );
    }
  }
}

【问题讨论】:

    标签: reactjs redux react-redux apollo


    【解决方案1】:

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

    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 并更新。你可能会遇到一些边缘情况,所以当事情似乎中断时不要忘记这个功能

    【讨论】:

    • 不幸的是,当我返回 null 时,我的网格会在加载时间内消失,直到我收到新数据。我想在查询完成加载之前将我的网格与我以前的数据保持一致。
    • 我更新了我的答案。我认为您可以为此使用 shouldcomponentupdate
    • 好的,现在它在应用程序启动时呈现 2 次(我认为这很正常)。我所做的第一个操作(更改页面)仅呈现一次(完成加载时)。但是在 第二次 我更改页面(或第三次或第四次或...)时,它会呈现 2 次(加载和未加载)。知道为什么吗?
    • 这很有意义......每次loading 标志更改时,您的减速器都会返回一个新的状态对象。您需要按值进行 deepEqual 比较。您可以使用 lodash 或一些具有 deepEqual 的类似库或自己编写。编辑我的评论
    • 实际上,我找到了一种使它与shouldComponentUpdate() 一起工作的方法。我在 render() 函数之前的 Container 中实现了这一点:shouldComponentUpdate (nextProps) { if (nextProps.data.loading === false) { return true; }else { return false; } }
    猜你喜欢
    • 2018-01-12
    • 2020-10-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多