reactjs - REACTJS 使用 fetch 通过 const 传递变量
问题描述
我的功能是从我正在使用的 openweather API 中获取一些东西。
const [ForecastFind, setForecastFind] = useState(null)
useEffect(() => {
fetch(
'https://api.openweathermap.org/data/2.5/onecall?lat=22&lon=151&exclude=current,minutely,daily&APPID=TOKEN',
)
.then(response => response.json())
.then(data => setForecastFind(data.hourly[0].dt))
}, [])
当我像这样使用它时,这很好用:
<div className="DescriptionsSplitter" style={{ marginTop: '-20vh' }}>
{ForecastFind}
</div>
我要做的是让它传入一个变量,这样我就可以通过函数访问我想要的任何索引。(data.hourly[0] ,我得到第一项)
我尝试过的是:这显然不是正确的语法,但我不确定正确的语法是什么。
const [ForecastFind, setForecastFind] = useState(null)
useEffect(choose => {
var choose = 0
fetch(
'https://api.openweathermap.org/data/2.5/onecall?lat=22&lon=151&exclude=current,minutely,daily&APPID=TOKEN',
)
.then(response => response.json())
.then(data => setForecastFind(data.hourly[choose].dt))
}, [])
尝试将 const 与变量一起使用:
<div className="DescriptionsSplitter" style={{ marginTop: '-20vh' }}>
{ForecastFind(1)}
</div>
解决方案
useEffect 不会在回调函数中传递任何参数。您可以做的是将整个数据存储在 ForecastFind 状态并调用一个函数来访问您需要的内容
const [ForecastFind, setForecastFind] = useState(null);
useEffect(() => {
var choose = 0;
fetch('https://api.openweathermap.org/data/2.5/onecall?lat=22&lon=151&exclude=current,minutely,daily&APPID=TOKEN')
.then(response => response.json())
.then(data => setForecastFind(data.hourly));
}, []);
const getForecast = (choose) => {
return ((ForecastFind || {})[choose] || {}).dt || null;
}
...
<div className="DescriptionsSplitter" style={{marginTop:'-20vh'}}>
{getForecast(1)}
</div>
推荐阅读
- ios - 来自 NSObject 类的 popToRootViewController
- css - 将我的 PE 统计信息设置为右侧的侧边栏
- c# - 异常'System.ArgumentException'
- deep-learning - 对 word2vec 嵌入的 One-hot 编码
- swift - Cloud Firestore 在我希望它快速创建数组时创建地图
- r - 如何轻松地将分组摘要的输出与数据的整体输出相结合
- spring - SingleConnectionDataSource 现在关闭新实例
- angular - 使用高图/高图悬停在工具提示上时如何显示同一属性的多个值
- powershell - 使用查询或 Powershell 在 SSAS 实例上识别具有管理访问权限的登录
- python - conda报错:环境不一致,请仔细查看打包方案