useEffect 中抛出错误未显示在屏幕上[关闭]

问题描述 投票:0回答:1

我有这个应用程序,您可以从 API 中获取电影,但如果您输入的电影不可用,它应该将错误视为数据。在这种情况下,响应为 false,因此如果它是 true,则错误应该是电影不是发现但如果我控制台记录错误,则不会显示错误。消息它只显示未定义,当我控制台记录错误时,它显示一个对象,但它是一个反应对象

 useEffect(
    function () {
      async function fetchMovie() {
        setIsLoading(true);
        try {
          setErrors("");
          const res = await fetch(
            `http://www.omdbapi.com/?apikey=${key}&s=${query}`
          );
          if (!res.ok) throw new Error("Network issue unable to fetch");

          const data = await res.json();

          if (data.Response === "False") {
            throw Error("Movie Not found");
          }

          setMovies(data.Search);
        } catch (error) {
          setErrors(error.message);
        } finally {
          setIsLoading(false);
        }
      }
      if (query.length < 3) {
        setMovies([]);
        setErrors("");
        return;
      }
      fetchMovie();
    },
    [query]
  );

我基本上尝试了所有方法,但它没有显示没有消息属性的错误

reactjs react-hooks try-catch
1个回答
0
投票

试试这个:

    useEffect(() => {
    // function () {  // delete this line and its close bracket, 
    // as you are calling fetchMovie() so no need for this wrapper, 
    // that's why your function is never called.
    async function fetchMovie() {
        setIsLoading(true);
        try {
        setErrors("");
        const res = await fetch(
            `http://www.omdbapi.com/?apikey=${key}&s=${query}`
        );
        if (!res.ok) throw new Error("Network issue: unable to fetch");

        const data = await res.json();

        if (data.Response === "False") {
            throw new Error("Movie not found");
        }

        setMovies(data.Search);
        } catch (error) {
        setErrors(error.message);
        } finally {
        setIsLoading(false);
        }
    }

    if (query.length < 3) {
        setMovies([]);
        setErrors("");
    }
    fetchMovie();
    }, [query, key]); // Include key as a dependency
© www.soinside.com 2019 - 2024. All rights reserved.