数据在反应列表中显示两次

data is getting diisplayed twice in list in react

我正在获取以下格式的数据。

[
  {
    "country_id": 1,
    "country_name": "INDIA",
    "insurance_id": {
      "insurance_id": 1,
      "insurance_name": "LIC",
      "createdAt": "2022-04-07T07:33:34.929Z",
      "modifiedAt": "2022-04-07T07:33:34.929Z",
      "deletedAt": null
    }
  },
  {
    "country_id": 2,
    "country_name": "INDIA",
    "insurance_id": {
      "insurance_id": 101,
      "insurance_name": "HDFC",
      "createdAt": "2022-04-07T07:33:09.698Z",
      "modifiedAt": "2022-04-07T07:33:09.698Z",
      "deletedAt": null
    }
  },
  {
    "id": "7e71625d-cf8e-4793-ba15-2d84338fde13",
    "createdAt": "2022-04-07T11:13:30.452Z",
    "modifiedAt": "2022-04-07T11:13:30.452Z",
    "deletedAt": null,
    "country_id": 3,
    "country_name": "PAKISTAN",
    "insurance_id": null
  }
  }
]

我需要在列表中显示 country_name。该值在上述数据中为 duplicate,因此即将 twice。我只需要在列表中显示一次。

下面是我的代码。

const [countryName, setCountryName]=useState([]);
const fetchCountry = async ()=>{
        const {data}= await httpClient.get( config.resourceServerUrl+"/country");
        data.length>0? setCountryName(data): setCountryName([]);
     }

我正在使用 react-select 组件来显示列表。

<Select
      id="country" 
      name="contry"   
      placeholder="Select the Country"
      className="align-items-center justify-content-center"
      options={countryName.map((country:Country)=>
             ({ label: country.country_name, value: country.id })
     )}
     onChange={selectInsurer}
  />

如何使此列表独一无二?

您可以创建一个包含文件中所有值的列表,甚至是重复的值,然后您可以参考这个 this 问题和已接受的答案,它向您展示了如何从中创建一个唯一列表包含重复项的列表。

您可以在将列表提供给 Select 组件之前对其进行预处理,如下所示:

const uniqueCountries = [];
for(let country of countryName){
   if(!uniqueCountries.find(c => c.country_name === country.country_name)){
      uniqueCountries.push(country);
   }
}

我将创建一个仅包含不同国家/地区名称的新列表,如下所示:

const countries = new Set()
obj.forEach(country => countries.add(country.country_name))
const list = Array.from(countries) // pass this array as options prop