[英]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.