[英]How to prevent React hooks from erasing previous data while loading?
我正在尝试反应钩子并制作了我的第一个组件。 除了加载数据时出现闪烁问题外,一切正常,这是我的组件(一个简单的文章列表,带有上一页/下一页分页):
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>
)
}
问题是:当点击 prev/next 按钮时,它会启动一个服务器请求, loading
自动设置为true
,而data
设置为undefined
。 数据未定义,加载时文章列表为空。 我可以使用loading
变量按条件显示微调器,但这是一个非常快的请求(不需要微调器),并且它不会阻止以前的数据消失,这是造成这种不需要的闪烁的原因。
知道如何处理这个问题吗? 谢谢 !
通过迁移到官方 @apollo/react-hooks 绑定解决,因为我使用的是https://github.com/trojanowski/react-apollo-hooks
免责声明:我没有经常使用 React 钩子,或者根本没有使用 Apollo。 这个答案是推测性的。
通过查看@apollo/react-hooks
的文档,我会尝试将查询的fetchPolicy
设置为network-only
。 这样,它不应该首先从缓存(为空)返回初始数据。
const { data, loading } = useQuery(gql(queries.InfoFeed), {
variables: {
offset: (articlesByPage * (currentIndex - 1))
},
fetchPolicy: 'network-only'
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.