axios Reactjs,typescript

dsf9zpds  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(100)

我试图使搜索栏,我可以获取作者和显示作者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;
zyfwsgd6

zyfwsgd61#

问题似乎是您依赖于typescript来推断API调用的类型。(相反,typescript将其推断为never,如果您尝试使用它,则始终会出错)
要解决这个问题,只需为获取数据设置一个类型

type fetchData = {
  id: number,
  author: string,
  width: number,
  height: number,
  url: string,
  download_url: string
}

然后将您的状态设置为

const [data, setData] = useState<fetchData[]>([]);
const [searchResults, setSearchResults] = useState<fetchData[]>([]);

完整代码

import { useEffect, useState } from "react";
import axios from "axios";

type fetchData = {
  id: number,
  author: string,
  width: number,
  height: number,
  url: string,
  download_url: string
}

function Searchbar() {
  const [query, setQuery] = useState("");

  const [data, setData] = useState<fetchData[]>([]);

  // Add one more state to store the authors being searched for

  const [searchResults, setSearchResults] = useState<fetchData[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      const res = await axios.get(`https://picsum.photos/v2/list`);
      setData(res.data);
    };
    fetchData();
  }, []);

  useEffect(() => {
    setSearchResults(
      data.filter((authorData : fetchData) =>
        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 key={author.id}>{author.author}</div>
        ))}
      </div>
    </div>
  );
}

export default Searchbar;

相关问题