【问题标题】:REACTJS Pass variable through const using fetchREACTJS 使用 fetch 通过 const 传递变量
【发布时间】:2021-07-01 22:59:24
【问题描述】:

我的函数在这里从我正在使用的 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>

【问题讨论】:

    标签: reactjs react-hooks fetch jsx


    【解决方案1】:

    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>
    

    【讨论】:

    • @Quentin 更新了帖子以处理该问题。但是,如果在获取数据之前不呈现依赖于 ForecastFind 的任何内容,则可以更好地处理,这是我假设 OP 根据他的帖子已经在做的事情
    • 这行得通,但由于某种原因 {getForecast(0)} 得到了第 3 项而不是第 1 项。一切都在索引中向前移动了 2。
    • 万一你在某处改变了预测数组
    • 我不在任何地方,我发布的上述代码在获取第 0 个索引项时有效。超级诡异
    • 记录 ForecastFind 数组并查看它是否记录了正确的数据可能是有意义的
    【解决方案2】:

    ForecastFind 不是函数,因此您不能传入参数。 我建议像setForecastFind(((data.hourly))) 一样将整个 data.hourly 数组存储在 ForecastFind 中。 然后就可以这样访问了-

    <div className="DescriptionsSplitter" style={{marginTop:'-20vh'}}>
       {ForecastFind[1].dt}
    </div>
    

    【讨论】:

      猜你喜欢
      • 2021-08-05
      • 2017-01-17
      • 2019-05-10
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      相关资源
      最近更新 更多