在我的App.js函数中,当它第一次加载时,我想获取一个网站。此网站包含.json数据。当我尝试获取网站时,控制台显示以下错误:
App.js:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch
App.JS:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch当我通过web浏览器访问网站时,我能够看到JSON。
我的App.js代码:
import logo from './logo.svg';
import './App.css';
import Weather from './Weather'
import React, { Component, useState } from "react";
function App() {
const [details, setDetails] = useState("0");
fetch("https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313")
.then(response => response.json())
.then((data) => {
setDetails(data)
console.log("hi")
} );
return (
<div className="App">
<div className="weatherWrap">
<Weather longg="0" lat="0" name="China"/>
</div>
</div>
);
}
export default App;我假设我获取的网站是错误的。我还认为,按照我的方式,它每次都会继续获取。而我只想让它获取一次。请告诉我怎么修。谢谢!
发布于 2021-02-15 12:03:37
试试下面这段代码:
const url = 'https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313';
function App() {
const [details, setDetails] = useState([]);
const getDetails = async()=>{
const response = await fetch(url);
const details = await response .json();
setDetails(details );
}
useEffect(() => {
getDetails();
},[]);
}发布于 2021-02-15 11:44:19
以下是为您工作的代码。Link
导入"./styles.css";从“react”导入{ useEffect,useState };
export default function App() {
const [details, setDetails] = useState("0");
useEffect(() => {
fetch(
"https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313"
)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}, []);
return (
<div className="App">
<div className="weatherWrap">hello world</div>
</div>
);
}https://stackoverflow.com/questions/66201802
复制相似问题