开发者问题收集

未捕获(在承诺中)axios react

2022-07-28
445

我正在尝试构建一个 Netflix 克隆,并在 Banner.js 文件的第 12 行获取未捕获的(在承诺中)AxiosError。问题是横幅根本不显示,“电影”为空。

Banner.js:

import axios from 'axios';
import React, { useEffect, useState} from 'react'
import requests from "./requests";

function Banner() {
  const [movie, setMovie] = useState([]);

  useEffect(() => {
    async function fetchData() {
        const request = await axios.get(requests.fetchNetflixOriginals);
        setMovie(
           request.data.results[
              Math.floor(Math.random() * request.data.results.length -1)
            ]
           );
        return request;
    }
    fetchData();
}, []);

console.log(movie);

return (
<header className="banner"
    style={{
        backgroundSize: "cover",
        backgroundImage: `url(
         "https://image.tmdb.org/t/p/original/${movie?.backdrop_path}"
         )`,
        backgroundPosition: "center center"
    }}
>

    <div className="banner__contents">
        <h1>{movie?.title || movie?.name || movie?.original_name}
        </h1>

       
    {/* description */}

    </div>
    
</header>
)
}

 export default Banner
3个回答

您应该像这样处理错误:

  1. 为错误创建一些状态:
const [error, setError] = useState(null);
  1. 将您的请求包装在 try/catch 中。
try {
       const request = await axios.get(requests.fetchNetflixOriginals);
       setError(null); // in case it had a value previously
       setMovie(
           request.data.results[
              Math.floor(Math.random() * request.data.results.length -1)
            ]
           );
        return request;
    } catch (err) {
      setError(err);
    }
  1. 如果存在错误,则呈现错误:
if (error) {
    return <div class="error">There was an error loading movies: {err}</div>
}
return <header...</header>
Ryan Wheale
2022-07-28

显然我应该从文件 axios './axios' 而不是库 'axios' 导入。谢谢帮助!

Chiprian Tutueanu
2022-07-28

首先,您必须将代码包装在 try 和 catch 块中以防止出现错误 然后您就会得到承诺,所以尝试一下

const data = await request.json()
MandanaMS
2022-07-28