async fetch 将数据两次推送到数组中

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

async fetch pushing data twice into array

问题

以下是你要的翻译部分:

我正在尝试使用fetch和异步箭头函数进行Rick & Morty API调用,但我发现该函数将接收到的元素推送两次到我的数组中。
我已经尝试过使用和不使用useEffect(我正在使用React与TypeScript),但没有结果,我不明白为什么该函数被调用两次。

有人可以解释为什么会发生这种情况吗?

期望输出:包含2个对象的数组(ID为1和2的行星)

实际输出:包含4个对象的数组(ID为1的行星出现两次,ID为2的行星也出现两次)

如果有人可以帮助我理解为什么会发生这种情况以及如何修复它,我将非常感激。

请注意,我已经将HTML和代码部分排除在外,只翻译了你提供的问题和期望输出。

英文:

I'm trying to make a Rick & Morty API call with fetch and an async arrow function, but I found that the function is pushing the elements received twice into my array.
I already tried to make the call with and without useEffect (I'm using React with TypeScript) but I got no results and I don't understand why the function is being called twice.

Anyone available to explain to me why this is happening?

data.ts:

import { PlanetInterface, ResidentsInterface } from "./data-interfaces";

export const planetsList: PlanetInterface[] = [];
export const residentsList: ResidentsInterface[] = [];

export const getPlanetById = async (planets: number[]) => {
  for (let planet of planets) {
    const response = await fetch(
      `https://rickandmortyapi.com/api/location/${planet}`
    );
    const planetData: PlanetInterface = await response.json();
    planetsList.push(planetData);
  }
  console.log(planetsList);
};

// export const getResidentsByPlanet = async (residents: string[]) => {
//   for (let resident of residents) {
//     const response = await fetch(resident);
//     const residentData = await response.json();
//     residentsList.push(residentData);
//   }
//   console.log(residentsList);
// };


app.tsx:

import { useEffect } from "react";
import { getPlanetById } from "./api/data";
import "./App.css";

function App() {
  useEffect(() => {
    getPlanetById([1, 2]);
  }, []);

  // getPlanetById([1, 2]);

  return <main className="container"></main>;
}

export default App;

Expected output: Array of 2 objects (planets with ID 1 and 2)

Received output: Array of 4 objects (planet with ID 1 twice and planet with ID 2 also twice)

If anyone can help me understand why this is happening and how I can fix it, I would be very grateful.

答案1

得分: 0

I guess you are using <React.StrictMode />
If you remove that, the function is called once as you expect.
Here is the document about strict mode
https://en.reactjs.org/docs/strict-mode.html

英文:

I guess you are using <React.StrictMode />

If you remove that, the function is called once as you expect.

Here is the document about strict mode
https://en.reactjs.org/docs/strict-mode.html

答案2

得分: 0

getPlanetById的设计可能不适合React,因为调用它会产生副作用,而且没有清理的方法,你应该将它包装成一个钩子(hook)或手动清理,这里是一个示例:

useEffect(() => {
    getPlanetById([1, 2]);
    return () => { planetsList.length = 0 }
}, []);
英文:

The design of that getPlanetById might be not suit for React since the call of it create a side effect and there is no way to clean it up, you should wrap it into a hook or do a manually clean up, here is an example:

useEffect(() => {
    getPlanetById([1, 2]);
    return () => { planetsList.length = 0 }
}, []);

huangapple
  • 本文由 发表于 2023年2月14日 09:10:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442601.html
匿名

发表评论

匿名网友

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

确定