处理 http 错误"React"



我是react的初学者。我正在做一个"处理Http错误"的项目。我想展示"哪里出了问题"。当HTTP响应状态为404,但它显示和错误:'response'没有定义。为什么?

function App() {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [err, setError] = useState(null);
const fetchMovieHandler = () => {
setIsLoading(true);
setError(null);
fetch("https://swapi.dev/api/film")
.then((response) => response.json())
.then((data) => setData(data.results.map((title) => title.title)));
setIsLoading(false);
if (response.status === 404) {
throw new Error("Something Went Wrong!");
}
};
return (
<div className="App">
<div className="fetch">
<button className="fetch_btn" onClick={fetchMovieHandler}>
Fetch Movies
</button>
</div>
{!isLoading && data.length > 0 && (
<div className="movies">
<h3> {data[0]}</h3>
<h3> {data[1]}</h3>
<h3> {data[2]}</h3>
<h3> {data[3]}</h3>
<h3> {data[4]}</h3>
<h3> {data[5]}</h3>
<h3> {data[6]}</h3>
</div>
)}
{isLoading && <p>Loading...</p>}
{!isLoading && data.length === 0 && <p> Found no Movies...</p>}
</div>
);
}
export default App;

您可以将response.status=404放入fetch子句中,因为您不必将response声明为钩子或变量

const location = useLocation();
const [Response, setResponse] = useState('');
const fetchMovieHandler = () => {
setIsLoading(true);
setError(null);
fetch("https://swapi.dev/api/film")
.then((response) =>{
if (response.status === 404) {
throw new Error("Something Went Wrong!");
}
}).then((data) => setData(data.results.map((title) => title.title)));

setIsLoading(false);

};


return (
<div className="App">
<div className="fetch">
<button className="fetch_btn" onClick={fetchMovieHandler}>
Fetch Movies
</button>
</div>
{!isLoading && data.length > 0 && (
<div className="movies">
<h3> {data[0]}</h3>
<h3> {data[1]}</h3>
<h3> {data[2]}</h3>
<h3> {data[3]}</h3>
<h3> {data[4]}</h3>
<h3> {data[5]}</h3>
<h3> {data[6]}</h3>
</div>
)}
{isLoading && <p>Loading...</p>}
{!isLoading && data.length === 0 && <p> Found no Movies...</p>}
</div>
)

};

最新更新