[英]Is there an implementation of infinite scroll with useEffect that doesn't trigger the react-hooks/exhaustive-deps lint warning?
I'm implementing an infinite scroll-like solution using React hooks. 我正在使用React钩子实现无限滚动式解决方案。 The following code shows what I'm trying to accomplish and a working example can be seen on codesandbox here . 下面的代码显示什么,我试图完成和工作的例子可以在codesandbox可以看出这里 。
I'm receiving an exhaustive-deps
warning in useEffect
because I haven't listed data
as a dependency (this would obviously cause an infinite loop). 我在useEffect
收到exhaustive-deps
警告,因为我没有将data
列为依赖项(这显然会导致无限循环)。 Is there a way to implement this kind of infinite scrolling solution without suppressing this warning? 有没有办法实现这种无限滚动解决方案而不会抑制此警告?
function App() {
const [data, setData] = useState([]);
const [page, setPage] = useState(0);
useEffect(() => {
const newData = getData(page);
setData([...data, ...newData]);
}, [page, setData]); // react-hooks/exhaustive-deps warning here
return (
<div>
Data:
<ul>
{data.map(el => (
<li>{el}</li>
))}
</ul>
<button onClick={() => setPage(page + 1)}>Load More</button>
</div>
);
}
You can pass a callback to receive the previous data. 您可以传递回调以接收以前的数据。
useEffect(() => {
const newData = getData(page);
setData(previousData => [...previousData, ...newData]);
}, [page, setData]);
Forked sandbox without warnings. 叉沙箱没有警告。
Unrelated to the warning above, also make sure to add key
prop for each item. 与上述警告无关,还要确保为每个项目添加key
道具。
<li key={el}>{el}</li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.