如何防止 React hooks 在加载时擦除以前的数据?
How to prevent React hooks from erasing previous data while loading?
我正在尝试反应挂钩并制作我的第一个组件。一切正常,除了加载数据时出现闪烁问题,这是我的组件(一个简单的文章列表,带有 prev/next 分页):
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
变量显示微调器条件,但这是一个非常快的请求(不需要微调器),并且它不会阻止以前的数据消失,这是造成这种不需要的闪烁的原因。
知道如何处理这个问题吗?谢谢!
免责声明:我没有太多使用 React hooks,或者根本没有使用 Apollo。这个答案是推测性的。
通过查看 the documentation for @apollo/react-hooks
,我会尝试将您的查询的 fetchPolicy
设置为 network-only
。这样,它不应该首先 return 来自缓存(空)的初始数据。
const { data, loading } = useQuery(gql(queries.InfoFeed), {
variables: {
offset: (articlesByPage * (currentIndex - 1))
},
fetchPolicy: 'network-only'
});
通过迁移到官方@apollo/react-hooks 绑定解决,因为我使用的是 https://github.com/trojanowski/react-apollo-hooks
我正在尝试反应挂钩并制作我的第一个组件。一切正常,除了加载数据时出现闪烁问题,这是我的组件(一个简单的文章列表,带有 prev/next 分页):
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
变量显示微调器条件,但这是一个非常快的请求(不需要微调器),并且它不会阻止以前的数据消失,这是造成这种不需要的闪烁的原因。
知道如何处理这个问题吗?谢谢!
免责声明:我没有太多使用 React hooks,或者根本没有使用 Apollo。这个答案是推测性的。
通过查看 the documentation for @apollo/react-hooks
,我会尝试将您的查询的 fetchPolicy
设置为 network-only
。这样,它不应该首先 return 来自缓存(空)的初始数据。
const { data, loading } = useQuery(gql(queries.InfoFeed), {
variables: {
offset: (articlesByPage * (currentIndex - 1))
},
fetchPolicy: 'network-only'
});
通过迁移到官方@apollo/react-hooks 绑定解决,因为我使用的是 https://github.com/trojanowski/react-apollo-hooks