javascript - 通过 React 传递 API 数据
问题描述
我有一个函数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>
);
}
推荐阅读
- angular - 在 GitHub 页面上部署了我的 Angular 应用程序,但在控制台中的网站上出现错误
- python - 从 N 个元素的拒绝采样中输出 N 个元素
- javascript - 添加后如何显示更新的数组?
- sorting - SAS:排序错误(按变量排序不正确)
- python - 如何将多个 csv 合并到一个数据框中
- java - 对于 XSSFCell 类型,方法 getCellTypeEnum() 未定义
- r - 打印到 pdf() 时,在 ggplot2 中的轴标签中使用短划线
- python - 如何根据单词对的存在来选择子字符串?Python
- java - Spring Boot,无法让 Hibernate 工作
- javascript - 如果返回 Google Apps 脚本 GoogleSheets