【问题标题】:Why does my react function function iterate twice?为什么我的react函数函数会迭代两次?
【发布时间】:2023-02-03 22:19:57
【问题描述】:

我目前正在尝试使用 PokeAPI 的项目。并使用his guide寻求帮助。在useEffect中调用函数迭代两次的问题,我也改不了。

当我在 useEffect 中使用 getAllPokemons 运行以下代码时

const PokeListPage = () => {
  const [layoutToggle, setLayoutToggle] = useState(false);

  const [allPokemons, setAllPokemons] = useState([]);
  const [loadPoke, setLoadPoke] = useState(
    "https://pokeapi.co/api/v2/pokemon?limit=20"
  );

  useEffect(() => {
    getAllPokemons();
    console.log(allPokemons);
  }, []);

  const getAllPokemons = async () => {
    const res = await fetch(loadPoke);
    const data = await res.json();
    setLoadPoke(data.next);

    function createPokemonObject(result) {
      result.forEach(async (pokemon) => {
        const res = await fetch(
          `https://pokeapi.co/api/v2/pokemon/${pokemon.name}`
        );
        const data = await res.json();
        setAllPokemons((currentList) => [...currentList, data]);
      });
    }
    createPokemonObject(data.results);
    console.log(allPokemons);
  };

我得到了 allPokemons 中前 20 个对象的双胞胎。查看输出:

enter image description here

但是当我删除该功能并使用按钮触发该功能时,它的行为符合预期。这意味着该函数为每个口袋妖怪使用一个对象填充 allPokemon 数组。见输出。

enter image description here

我已经尝试了从其他存储库复制整个文件的所有方法,并且我不知道我是否遵循了不同的教程,但是问题仍然存在。有谁知道为什么?

【问题讨论】:

  • 在产品离子或本地?

标签: javascript reactjs pokeapi


【解决方案1】:

可能是因为您正在将您的应用渲染成React.严格模式运行特定功能和方法两次的组件,以帮助您检测意外的副作用。由于副作用是状态 update.so,这会触发重新渲染。

用一个使用效果在组件安装时运行一次效果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 2011-12-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多