[英]React with Typescript .filter gives me error
So, I am trying to filter data from an API, but i am new with Typescript and I cannot fix this error: Property 'filter' does not exist on type 'string'.
所以,我正在尝试从 API 过滤数据,但我是 Typescript 的新手,我无法修复此错误:
Property 'filter' does not exist on type 'string'.
function App() {
const [coins, setCoins] = useState<string>('')
const [search, setSearch] = useState<string>('')
useEffect(()=>{
axios
.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false')
.then(res =>{
setCoins(res.data)
console.log(res.data)
})
.catch(error=>console.log(error))
},[]);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value)
}
const filteredCoins = coins.filter((coin: any) =>
coin.name.toLowerCase().includes(search.toLowerCase())
);
return (
<div className='coin-app'>
<div className='coin-search'>
<h1 className='coin-text'>Search a currency</h1>
<form>
<input
className='coin-input'
type='text'
onChange={handleChange}
placeholder='Search'
/>
</form>
</div>
{filteredCoins.map((coin: any) => {
return (
<Coin
key={coin.id}
name={coin.name}
price={coin.current_price}
symbol={coin.symbol}
marketcap={coin.total_volume}
volume={coin.market_cap}
image={coin.image}
priceChange={coin.price_change_percentage_24h}
/>
);
})}
</div>
);
}
Could someone help?有人可以帮忙吗? I tried to make the useState an array, but it still gives me this error.
我试图使 useState 成为一个数组,但它仍然给我这个错误。 I am very confused to be honest.
老实说,我很困惑。
this is the line:这是行:
const filteredCoins = coins.filter((coin: any) =>
You declare coins
as a string
:您将
coins
声明为string
:
const [coins, setCoins] = useState<string>('')
and then expect it to be an array here:然后期望它在这里是一个数组:
const filteredCoins = coins.filter((coin: any) =>
If you want the coins
state to be an array of objects, then you have to declare it as such.如果您希望
coins
state 是一个对象数组,那么您必须这样声明它。
interface Coin {
name: string
}
const [coins, setCoins] = useState<Coin[]>([])
And now you would filter it like so:现在你可以像这样过滤它:
const filteredCoins = coins.filter((coin) =>
coin.name.toLowerCase().includes(search.toLowerCase())
);
Note, you don't need to manually set a type for coin
here.请注意,您无需在此处手动设置
coin
的类型。 Typescript knows what type is in the array, so it will set coin
to the correct type without your help. Typescript 知道数组中的类型,因此它会在没有您帮助的情况下将
coin
设置为正确的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.