在React中使用useEffect的无限循环

时间:2020-04-11 12:06:06

标签: reactjs infinite-loop use-effect

这是我的组件:

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的第二个参数

2 个答案:

答案 0 :(得分:1)

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

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

那应该可以解决您的问题。

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

答案 1 :(得分:1)

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

几种可能性:

1)过滤出重复项。如果您不在乎那些“总计:”条目,那是最好的选择。

if (response.status === 200) {
  const newCountriesArray = [...countriesArray];
  const data = await response.json();
  data.forEach(item => {
    if (item.country !== "Total:") {
      newCountriesArray.push(item.country)
    }
  });
  setCountriesArray(newCountriesArray);
}

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

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