React中具有useEffect的无限循环

问题描述 投票:0回答:1

这是我的组件:

import React, { useState, useEffect } from "react";

export default function App() {
  const [countriesArray, setCountriesArray] = useState([]);

  useEffect(() => {
    getCountriesArray();
  }, []);

  const getCountriesArray = async () => {
    try {
      let response = await fetch(
        "https://coronavirus-19-api.herokuapp.com/countries"
      );
      if (response.status === 200) {
        const newCountriesArray = [...countriesArray];
        const data = await response.json();
        await data.forEach(item => newCountriesArray.push(item.country));
        setCountriesArray(newCountriesArray);
      } else {
        setErrorStatus(true);
        console.error("Error status");
      }
    } catch (err) {
      console.error(err);
    }
  };

  const optionItems = countriesArray.map((item) =>
        <option key={item}>{item}</option>
    )

  return (
    <div className="App">
      <select>{optionItems}</select>
    </div>
  );
}

在选择时,我在安装组件时得到了国家的名称,但是在控制台中,我收到了循环错误消息:

Warning: Encountered two children with the same key, `Total:`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
    in select (at App.js:36)
    in div (at App.js:35)
    in App
    in StrictMode (at src/index.js:8)

但是我将空数组用作useEffect的第二个参数,仅在安装组件时才执行它

reactjs infinite-loop use-effect
1个回答
0
投票

您可以通过这种方式使用地图本身提供的密钥:

const optionItems = countriesArray.map((item, key) =>
    <option key={key}>{item}</option>
)

应该可以解决您的问题。

顺便说一下,这不是一个无限循环问题,它是映射函数中的重复键。


0
投票

该错误与效果的依赖项数组无关。问题在于国家/地区在该数据中不是唯一的。 json包含7个条目,其中country === "Total:"

几个可能性:

1)筛选出重复项。如果您不在乎那些“总计:”条目,则为最佳选择。

2)使用其他键。由于此数据没有唯一键,因此您可能需要使用数组的索引。请注意,如果您打算对该列表进行排序,这将不是一个好的选择。

© www.soinside.com 2019 - 2024. All rights reserved.