[英]Property does not exist in typescript react
我正在嘗試通過 map 呈現來自“其他國家”api 的信息,但我的 typescript 無法識別我的數組中包含該信息的類型。
errors : "Property 'name' does not exist on type 'never'."
"Property 'population' does not exist on type 'never'."
"Property 'region' does not exist on type 'never'."
"Property 'flags' does not exist on type 'never'."
import * as C from './styles';
import { useEffect, useState } from 'react';
import Input from '../../components/Input';
import { api } from '../../api';
import { CountriesTS } from '../../types/Countries';
import CountryItem from '../../components/CountryItem';
const Countries = () => {
const [countries, setCountries] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
getAllCountries()
}, [])
const getAllCountries = async () => {
setLoading(true);
const resultCountries = await api.getCountries();
setCountries(resultCountries);
setLoading(false);
console.log(countries);
}
return (
<C.CountriesArea>
<Input />
<div className="countries">
{loading &&
<div className=''>Carregando...</div>
}
{!loading &&
countries.map((item) => (
<CountryItem
name={item.name}
population={item.population}
region={item.region}
capital={item.capital}
flag={item.flags.png}
/>
))
}
</div>
</C.CountriesArea>
)
}
export default Countries
國家項目文件夾:
import { CountryItemTS } from '../../types/CountryItem';
import { Link } from 'react-router-dom';
const CountryItem = ({name, population, region, capital, flag}: CountryItemTS) => {
return (
<C.CountryItem>
<Link to={`country/${name}`}>
<div className="img--area">
<img src={flag} alt={`Bandeira do País: ${name}`} />
</div>
<div className="data--area">
<p className="country--name">{name}</p>
<p>Population: <span>{population}</span></p>
<p>Region: <span>{region}</span></p>
<p>Capital: <span>{capital}</span></p>
</div>
</Link>
</C.CountryItem>
)
}
export default CountryItem
API 文件夾:
import axios from "axios";
const http = axios.create({
baseURL: 'https://restcountries.com/v3.1/'
})
export const api = {
getCountries: async () => {
let response = await http.get('/all')
return response.data
},
getCountry: async (name: string) => {
let response = await http.get(`/name/${name}?fullText=true`)
return response.data
},
getCountryByCode: async (code: string) => {
let response = await http.get(`/alpha?codes=${code}`)
return response.data
}
}
輸入 CountryItemTS 文件夾:
export interface CountryItemTS {
name: string,
capital: string,
population: number,
region: string,
flag: string,
}
由於您使用空數組啟動countries
地區,因此 TypeScript 不知道它是哪種類型。 執行以下操作為countries
指定類型。
const [countries, setCountries] = useState<CountryItemTS[]>([]);
在“國家”組件中,國家 state 的初始化應該是這樣的類型
const [countries, setCountries] = useState<CountryItemTS[]>([]);
如果在 state countries
/地區收到的密鑰與我在行flag={item.flags.png}
中注意到的不同,
然后你可以像這樣聲明一個新接口:-
interface ICountries extends CountryItemTS{
flags: { png: string };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.