通过 React 传递 API 数据
Passing API data through React
我有一个函数 getData()
可以获取当前天气状况的 JSON 对象。虽然我可以在控制台中看到 JSON 对象,但我似乎无法将它传递给可用变量。我在这里错过了什么?
const getData = () => {
let url = `https://api.openweathermap.org/data/2.5/weather?q=Asheville&appid=${key}`
fetch(url)
.then((response) => {
return response.json();
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
})
}
function App() {
let data = getData();
console.log(data);
return (
<div className="App">
<Forecast />
</div>
);
}
我已经尝试了几种方法,但无法正常工作。同样出于某种原因,它两次登录控制台,我不确定为什么。非常感谢任何建议!
你可以使用反应钩子
const useGetData = () => {
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
let url = `https://api.openweathermap.org/data/2.5/weather?q=Asheville&appid=${key}`;
fetch(url)
.then((response) => response.json())
.then((response) => setData(response))
.catch((err) => setError(err));
}, []);
return [data, error];
};
function App() {
let [data, error] = useGetData();
return (
<div>
<p>{JSON.stringify(data, null, 2)}</p>
{error && <p>There's been an error: {error}</p>}
</div>
);
}
我有一个函数 getData()
可以获取当前天气状况的 JSON 对象。虽然我可以在控制台中看到 JSON 对象,但我似乎无法将它传递给可用变量。我在这里错过了什么?
const getData = () => {
let url = `https://api.openweathermap.org/data/2.5/weather?q=Asheville&appid=${key}`
fetch(url)
.then((response) => {
return response.json();
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
})
}
function App() {
let data = getData();
console.log(data);
return (
<div className="App">
<Forecast />
</div>
);
}
我已经尝试了几种方法,但无法正常工作。同样出于某种原因,它两次登录控制台,我不确定为什么。非常感谢任何建议!
你可以使用反应钩子
const useGetData = () => {
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
let url = `https://api.openweathermap.org/data/2.5/weather?q=Asheville&appid=${key}`;
fetch(url)
.then((response) => response.json())
.then((response) => setData(response))
.catch((err) => setError(err));
}, []);
return [data, error];
};
function App() {
let [data, error] = useGetData();
return (
<div>
<p>{JSON.stringify(data, null, 2)}</p>
{error && <p>There's been an error: {error}</p>}
</div>
);
}