简体   繁体   English

如何防止 React 钩子在加载时删除以前的数据?

[英]How to prevent React hooks from erasing previous data while loading?

I'm trying react hooks and made my first component.我正在尝试反应钩子并制作了我的第一个组件。 Everything is working fine except a flickering problem wile data is loading, here's my component (a simple list of articles, with prev/next pagination) :除了加载数据时出现闪烁问题外,一切正常,这是我的组件(一个简单的文章列表,带有上一页/下一页分页):

function InfoFeed ({ limit, uuid }) {
  const [currentIndex, setCurrentIndex] = useState(1)
  const { data, loading } = useQuery(gql(queries.InfoFeed), {
    variables: {
      offset: (articlesByPage * (currentIndex - 1))
    }
  })
  const { articles } = data

  const incrementCb = () => setCurrentIndex(currentIndex === maxPaginationIndex ? 1 : currentIndex + 1)
  const decrementCb = () => setCurrentIndex(currentIndex === 1 ? maxPaginationIndex : currentIndex - 1)

  return (
    <Panel title="Fil Info">
      <StyledList>
        {articles && articles.map((article, index) => (<InfoItem key={index} article={article}/>))}
      </StyledList>
      <button onClick={incrementCb}>next</button>
      <button onClick={decrementCb}>prev</button>
    </Panel>
  )
}

The problem is : when clicking on prev/next buttons, it launches a server request, loading is automatically set to true , and data is set to undefined .问题是:当点击 prev/next 按钮时,它会启动一个服务器请求, loading自动设置为true ,而data设置为undefined Data being undefined, the article list is empty while loading.数据未定义,加载时文章列表为空。 I could show a spinner conditionnaly using the loading variable, but it's a pretty fast request (no spinner required), and it wouldn't prevent the previous data from disappearing, which is the cause of this unwanted flickering.我可以使用loading变量按条件显示微调器,但这是一个非常快的请求(不需要微调器),并且它不会阻止以前的数据消失,这是造成这种不需要的闪烁的原因。

Any idea how to deal with this ?知道如何处理这个问题吗? Thanks !谢谢 !

通过迁移到官方 @apollo/react-hooks 绑定解决,因为我使用的是https://github.com/trojanowski/react-apollo-hooks

DISCLAIMER: I have not used React hooks much, or Apollo at all.免责声明:我没有经常使用 React 钩子,或者根本没有使用 Apollo。 This answer is speculative.这个答案是推测性的。

From looking at the documentation for @apollo/react-hooks , I would try setting the fetchPolicy for your query to network-only . 通过查看@apollo/react-hooks的文档,我会尝试将查询的fetchPolicy设置为network-only That way, it shouldn't return the initial data from the cache (which is empty) first.这样,它不应该首先从缓存(为空)返回初始数据。

const { data, loading } = useQuery(gql(queries.InfoFeed), {
  variables: {
    offset: (articlesByPage * (currentIndex - 1))
  },
  fetchPolicy: 'network-only'
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM