我无法使用React钩子的`set`方法来更新状态。

huangapple go评论64阅读模式
英文:

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);
}

huangapple
  • 本文由 发表于 2023年5月29日 00:11:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定