【发布时间】:2021-09-05 14:33:26
【问题描述】:
我有一个非常简单的网站,我使用的是基于 React 的,托管在 Firebase 上。在 localhost 和我的托管站点上,我有一个加载 API 的页面。每当我加载该 API 时,该页面通常在第一次尝试后停止工作,有时它根本不起作用,直到我将 return 语句更改为空并再次返回。我正在使用类组件,但从未发生过错误,但我无法访问数据中的大量信息。
问题:我的钩子没有设置状态,数据。
错误:TypeError: Cannot read property 'volumeInfo' of null
问题:如何在每次页面加载时调用我的钩子?
交叉引用错误:No response from Fetch API in React useEffect hook 我看了这篇文章,希望得到指导,但它仍然没有加载。
代码:
import '../App.css';
import Navigation from './Navigation';
import React, { useState, Component, useEffect } from 'react';
import { NavLink } from 'react-router-dom';
const Milestone1 = () => {
const [data, setData] = useState(null);
useEffect(() => {
const callAPI = async () => {
try {
fetch("https://www.googleapis.com/books/v1/volumes/Wfan6L9RGgYC")
.then((res) => res.json())
.then((data) => setData(data));
} catch (e) {
console.log(e);
}
};
callAPI();
}, []);
console.log(data);
return <>{(
<div className="school">
<header className="App-header">
</header>
<center>
<div className="navigation">
<Navigation />
</div>
<body className="App-body">
<body className="App-body">
<h2>Milestone 1</h2>
<h5>Title: {data && data.volumeInfo.title}</h5>
<img src={data.volumeInfo.imageLinks.smallThumbnail} alt="image" />
<h5>Authors: {data && data.volumeInfo.authors} Publish info: {data && data.volumeInfo.publisher} {data && data.volumeInfo.publishedDate} Country: {data && data.saleInfo.country}</h5>
<h5>Rating: {data && data.volumeInfo.averageRating}</h5>
</body>
<NavLink to="/Milestone1part2">Milestone 1 part two</NavLink><br></br>
</body>
</center>
</div>
)}</>;
}
export default Milestone1;
我的另一个愚蠢的钩子:
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://www.googleapis.com/books/v1/volumes/Wfan6L9RGgYC")
.then((res) => res.json())
.then((data) => setData(data));
}, []);
我读过类似的帖子,通常它们在页面中有一个按钮或可以调用 API 的东西,但 1)它不是交互式页面 2)整个页面没有加载。
提前致谢。
【问题讨论】:
标签: reactjs react-native react-hooks