首页 > 解决方案 > 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>

标签: reactjsreact-hooksfetchjsx

解决方案


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>

推荐阅读