为什么每当我键入不存在的内容时,都会出现此错误?

Why whenever I type something that does not exist, i got this error?

每当我键入 json 中不存在的内容时,我都会收到此错误:

TypeError: countries.map is not a function

在我输入不存在的结果之前,搜索功能工作正常。

const mainUrl = `https://restcountries.eu/rest/v2/`
const all = `${'all'}`
const serachUrl = `${'name/'}`

const Home = () => {
  // usesstate to conutries
  const [countries, setCountries] = useState([])
  // usesstate to query
  const [query, setQuery] = useState('')

  {
    /* // fetch countries */
  }
  const fetchCountries = async () => {
    let url
    if (query) {
      url = `${mainUrl}${serachUrl}${query}`
    } else {
      url = `${mainUrl}${all}`
    }
    try {
      const response = await fetch(url)
      const data = await response.json()
      setCountries(data)
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    fetchCountries()
  }, [query])

问题

当您搜索不存在的内容时,API 返回一个错误对象,即 404。

{
  "status": 404,
  "message": "Not Found"
}

这存储在 countries 状态,然后您尝试映射它,OFC 抛出错误。

解决方案

Checking that the fetch was successful

A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server-side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true.

fetch API returns 即使有 400 个响应也已解决的 Promise。您应该检查请求是否成功。

const fetchCountries = async () => {
  let url;
  if (query) {
    url = `${mainUrl}${serachUrl}${query}`;
  } else {
    url = `${mainUrl}${all}`;
  }
  try {
    const response = await fetch(url);
    if (!response.ok) { // <-- check OK response
      throw new Error("Network response was not ok");
    }
    const data = await response.json();
    setCountries(data);
  } catch (error) {
    console.log(error);
  }
};