English 中文(简体)
根据ches子更新国家
原标题:Updating state based on fetches

I m trying to fetches movies OMDB API data you can see 2 fetches, each fetch give array of 10 objects data only,
but the data is being incremented on every search, even though I kept i.e reseting state setmovieData([]) at the beginning of the function.

useEffect(
  function () {
    async function requestMovieData() {
      setmovieData([]);
      const res1 = await fetch(
        `http://www.omdbapi.com/?apikey=51b8382f&s=${query}`,
      );
      const res2 = await fetch(
        `http://www.omdbapi.com/?apikey=51b8382f&s=${query}&page=1`,
      );

      const data1 = await res1.json();
      const data2 = await res2.json();

      if ((data1.Response = "True" && data1.Search)) {
        setmovieData([...movieData, ...data1.Search]);
      }
      if ((data2.Response = "True" && data2.Search)) {
        setmovieData([...movieData, ...data2.Search]);
      }
    }

    requestMovieData();
  },
  [query],
);
问题回答

这里有几个问题......

  1. State changes are asynchronous so setmovieData([]) may not be applied by the time you add more data
  2. Along the same lines, setting state based on previous state like with setmovieData([...movieData, ...data1.Search]) can have unforeseen effects as the current state may not be what you think

一般来说,你可以使用updater function,以避免点2,但我会建议一度收集和收集所有数据,然后在不担心数据是什么或什么的情况下说明数据。

// Stand-alone function that can be defined outside your component
const fetchMovies = async (query, page) => {
  const params = new URLSearchParams({
    apikey: "51b8382f",
    s: query,
  });
  if (page) {
    params.append("page", page);
  }

  const res = await fetch(`http://www.omdbapi.com/?${params}`);
  if (!res.ok) {
    throw new Error(`Fetch failed: ${res.status} ${res.statusText}`);
  }
  const { Response, Search } = await res.json();
  return Response === "True" ? Search : [];
};
useEffect(() => {
  Promise.all([fetchMovies(query), fetchMovies(query, 1)])
    .then((movies) => setmovieData(movies.flat()))
    .catch(console.error);
}, [query]);




相关问题
Asynchronous data loading in Entity-Framework?

Did anyone hear about asynchronous executing of an EF query? I want my items control to be filled right when the form loads and the user should be able to view the list while the rest of the items ...

Does PHP support asynchronous programming?

I m new to PHP. I am familiar with ASP.NET which support asynchronous programming. That is, if one request needs to do some I/O job. It is suggested to program the web page with BeginProcess/...

How to cancel an asynchronous call?

How to cancel an asynchronous call? The .NET APM doesn t seem to support this operation. I have the following loop in my code which spawns multiple threads on the ThreadPool. When I click a button on ...

What can cause select to block in Python?

Here s a snippet of code I m using in a loop: while True: print loop rlist, wlist, xlist = select.select(readers, [], [], TIMEOUT) print selected # do stuff At a certain point, ...

热门标签