英文:
I am not able to update state using set method react hooks
问题
我正在进行GET API调用以接收无限滚动的数据。因此,每当滚动条达到特定位置时,它会执行GET调用以获取更多数据。所以我需要每次在这里更新偏移量,但setOffset(prevOffset => prevOffset + 1)
不起作用,而且保持为初始值(0)用于下一次调用。然而,我能够使用setImages(prevImages => [...prevImages, ...data])
将新数据合并到现有数据中,新数据意味着在这里获取相同的数据,因为偏移量没有得到更新。
我想要每次API调用时更新偏移值。
英文:
I am doing GET api call to receive data for infinite scrolling. So every time the scrollbar reaches to particular position, it does a GET call to fetch more data. So I need to update the offset every time here, but setOffset(prevOffset => prevOffset + 1)
is not working, and remaining to initial value(0) for next calls. However, I am able to merge new data with the existing one using setImages(prevImages => [...prevImages, ...data])
, New data means its fetching the same data here as offset is not getting updated.
I want to update offset value with each api call.
import { useEffect, useState } from 'react';
function App() {
const API_KEY = '***';
const API_BASE_URL = 'https://api.giphy.com/v1/gifs/search';
const [images, setImages] = useState([]);
const [offset, setOffset] = useState(0);
const handleScroll = () => {
if (window.innerHeight + document.documentElement.scrollTop !== document.documentElement.offsetHeight)
{
return;
}
fetchData();
}
const createURL = () => {
const url = new URL(API_BASE_URL);
url.searchParams.set('q', 'hello');
url.searchParams.set('api_key', API_KEY);
console.log('lets print offset', offset);
url.searchParams.set('offset', offset);
return url;
}
const fetchData = async () => {
try {
const response = await fetch(createURL());
const { data, pagination } = await response.json();
console.log('lets print', pagination);
setImages(prevImages => [...prevImages, ...data]);
setOffset(prevOffset => prevOffset + 1);
} catch(error) {
console.error(error);
}
}
useEffect(() => {
fetchData();
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [])
return (
<div className="container">
<h1>Testimonials</h1>
<div className="testimonialContainer">
{images.map((image,idx) => {
return (
<p key={idx} className="testimonial">{image.title}</p>
)
})}
</div>
</div>
);
}
export default App;
答案1
得分: 0
封闭问题(过时的封闭)。有一个可以使用useRef
的简单技巧。
const [offset, setOffset] = useState(0);
const offsetRef = useRef();
offsetRef.current = offset;
...
const createURL = () => {
...
url.searchParams.set('offset', offsetRef.current);
}
英文:
Closure problem (stale closure). There is a simple trick with useRef
you can use.
const [offset, setOffset] = useState(0);
const offsetRef = useRef();
offsetRef.current = offset;
...
const createURL = () => {
...
url.searchParams.set('offset', offsetRef.current);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论