我试图使搜索栏,我可以获取作者和显示作者ID和图片,为什么我得到这个错误在我的代码:
类型“never”上不存在任何属性“toLowerCase”
import { useEffect, useState } from 'react';
import axios from 'axios';
function Searchbar() {
const [query, setQuery] = useState('');
const [data, setData] = useState([]);
// Add one more state to store the authors being searched for
const [searchResults, setSearchResults] = useState([]);
useEffect(() => {
const fetchData = async () => {
const res = await axios.get(`https://picsum.photos/v2/list`);
setData(res.data);
};
fetchData();
}, []);
useEffect(() => {
setSearchResults(
data.filter((authorData) =>
authorData['author'].toLowerCase().includes(query)
)
);
}, [query, data]);
return (
<div className='app'>
<input
className='search'
placeholder='Search...'
onChange={(e) => setQuery(e.target.value.toLowerCase())}
/>
<div>
{searchResults.map((author) => (
<div>{author}</div>
))}
</div>
</div>
);
}
export default Searchbar;
1条答案
按热度按时间zyfwsgd61#
问题似乎是您依赖于typescript来推断API调用的类型。(相反,typescript将其推断为
never
,如果您尝试使用它,则始终会出错)要解决这个问题,只需为获取数据设置一个类型
然后将您的状态设置为
完整代码