处理 React.js 中的错误

handle errors in React.js

没有结果或找不到图书时如何处理错误?

我有以下代码:

     //states input query
  const [query, setQuery] = useState('');

  //create the states for books
  const [book, setBooks] = useState([]);

  const handleChange = (e) => {
    const query = e.target.value;
    setQuery(query);
  }
const handleSubmit = (e) => {
    e.preventDefault();
    
    axios
      .get(`https://www.googleapis.com/books/v1/volumes?q=${query}&maxResults=40`)
      .then((res) => {
       console.log(res.data.items);
        setBooks(res.data.items);
      })
      .catch((err) => {
        console.log(err.response);
      });
}

const bookAuthors = (authors) => {
  if (!authors) return " Author not available ";
  if (authors.length <= 2) {
    authors = authors.join(" and ");
  } else if (authors.length > 2) {
    let lastAuthor = " and " + authors.slice(-1);
    authors.pop();
    authors = authors.join(", ");
    authors += lastAuthor;
  }
  return authors;
};





我想处理以下情况下的任何错误:

  1. 结果 = 0

我需要添加什么才能让它运行良好?

将错误作为一种状态 const [error, setError] = useState(false);

并在您的 catch 语句中调用 setError。 如果 error 不是 false.

,则显示错误