我想从头开始构建无限滚动。这是代码:
import React,{useEffect, useRef, useState} from 'react';
const Container:React.FC<{}> = () => {
const containerRef = useRef<HTMLDivElement | null>(null)
const [ scrollNumber, setScrollNumber ] = useState<number>(1);
const [posts, setPosts] = useState<any[]>([]);
useEffect(() => {
async function main(){
const req = await fetch('https://jsonplaceholder.typicode.com/posts');
const result = await req.json();
const pst = result.splice(0,10*scrollNumber);
setPosts(pst)
function scrollHandler(){
if(containerRef.current?.getBoundingClientRect().bottom === window.innerHeight){
console.log("Salam", scrollNumber);
setScrollNumber(scrollNumber + 1);
}
}
window.addEventListener("scroll", scrollHandler);
return () => window.removeEventListener("scroll", scrollHandler);
}
main()
},[])
useEffect(() => {
const loadData = async () => {
const req = await fetch('https://jsonplaceholder.typicode.com/posts');
const result = await req.json();
const pst = result.splice(0,10*scrollNumber);
setPosts(pst)
}
loadData()
},[scrollNumber])
return (
<div ref={containerRef}>
{posts.map(post => (
<div key={post.id}>
<br/>
<h1>{post.title}</h1>
(<p>{post.body}</p>)
<code>{post.userId}</code>
<br/><br/>
<hr/>
</div>
))}
</div>
)
}
export default Container
但有一个问题。当我测试它时。它总是更新为 2 没有其他。我搜索了一下。我发现window.addEventListener只记住initialState,这就是state总是更新为2的原因。但我找不到任何代码解决方案。
当年话下
相关分类