【问题标题】:Is my useEffect used correctly in fetching the weather data?我的 useEffect 是否正确用于获取天气数据?
【发布时间】:2021-11-28 20:41:09
【问题描述】:
import React,{ useState, useEffect } from 'react'
import axios from 'axios'

const App = () => {

  const [ countries, setCountries ] = useState([])
  const [ search, setSearch ] = useState('')
  const [ weather, setWeather ] = useState({})
  const [ capital, setCapital ] = useState('')

  const api_key = process.env.REACT_APP_API_KEY

  const searchedCountries = countries.filter(country =>
    country.name.common.toLowerCase().includes(search.toLowerCase()))

  useEffect(() => {
    axios
      .get('https://restcountries.com/v3.1/all')
      .then( response => {
        setCountries(response.data)
      })
  },[])

  useEffect(() => {
    const url = `http://api.weatherstack.com/current?access_key=${api_key}&query=${capital}`

      axios
      .get(url)
      .then(response => {
        setWeather(response.data)
        console.log('logged weather', response.data)
        console.log('capital inside: ', capital)
      })
    
  },[search])

  console.log(searchedCountries)

  const handleSearch = (event) => {
    setSearch(event.target.value)

    if(searchedCountries.length === 1){
      setCapital(searchedCountries[0].capital[0])
      console.log('capital is set', capital)
    }
    else
      setCapital('')
  }

  const handleShow = (event) => {
    event.preventDefault()
    setSearch(event.target.value)
  }

  if(searchedCountries.length > 10){
    return(
      <>
        <div>
          find countries
          <input value = {search} onChange = {handleSearch} />  
        </div>
        <p>Too many matches, specify another filter</p>
      </>
    )
  }else{
    if(searchedCountries.length === 1){
      const languages = Object.keys(searchedCountries[0].languages)
      console.log(typeof weather, weather)

      return(
        <>
          <div>
            find countries
            <input value = {search} onChange = {handleSearch} />  
          </div>
          <h1>{searchedCountries[0].name.common}</h1>
          <p>capital {searchedCountries[0].capital[0]}</p>
          <p>population {searchedCountries[0].population}</p>
          <h2>languages</h2>
          <ul>
            {languages.map(language => 
              <li key = {language}>{searchedCountries[0].languages[language]}</li>)}
          </ul>
          <img src= {searchedCountries[0].flags.png} alt= 'flag' />
          <h2>Weather in {searchedCountries[0].capital[0]}</h2>
          {/* <p><strong>temperature: </strong> {weather.current.temperature}  Celcius</p> */}
        </>
      )
    }else{
      return(
        <>
          <div>
            find countries
            <input value = {search} onChange = {handleSearch} />  
          </div>
          {searchedCountries.map( (country, index) => {
            return(
              <div key = {country.name.official}>{country.name.common}
                <button onClick = {handleShow} value = {country.name.common} >show</button>
              </div>
            )
          })}

        </>
      )
    }
  }
}

export default App

例如: 我输入了“fin”, 对象仍然是空的。 输入“finl”后, 天气变量包含赫尔辛基的天气数据。(我的每月使用量已达到极限,为什么示例图片的weather.success值为false。

如果我在我的代码中取消注释注释行,应用程序会在您输入“fin”后崩溃。

我想在这个应用程序中使用天气 API 中的数据而不会遇到错误。

你能帮我解决这个问题吗? 我是一名初学者,正在学习 React,以及 React 与 API 的交互。

感谢您的理解。

【问题讨论】:

    标签: javascript node.js reactjs api axios


    【解决方案1】:

    问题

    weather 在初始渲染时是一个空对象:

    const [ weather, setWeather ] = useState({});
    

    因此尝试更深入地访问对象会引发错误。

    例子:

    weather                     // {}
    weather.current             // undefined
    weather.current.temperature // error, cannot access X of undefined
    

    解决方案

    1. 您可以为正在访问的内容提供有效的初始初始状态,这样就不会为未定义/空访问引发错误:

       const [ weather, setWeather ] = useState({ current: {} });
      

      请注意,您可能还需要执行以下操作,以确保您在任何后续渲染中都没有未定义/空访问。

    2. 使用可选链接/保护子句来防止未定义/空访问。

      • 可选链接:weather?.current?.temperature
      • 保护子句:weather &amp;&amp; weather.current &amp;&amp; weather.current.temperature

    【讨论】:

    • 另外,另一个问题是,输入似乎是一个字符的延迟。这是为什么呢?
    • @spademarck React 状态更新是异步处理的。如果您在入队后立即记录状态,您将看到未更新的状态。
    • 我能做些什么来摆脱这种延迟。如果我不对变量使用 useState 会更好吗?
    • @spademarck 哪个输入/状态被延迟了?我再次仔细研究您的代码并试图了解为什么您同时拥有search 和capital 状态。 search 是 useEffect 挂钩的依赖项,但未引用,而是在 GET 请求中使用 capital。你能澄清一下你具体指的是什么吗?
    • 我有 search 来捕获输入元素的值,并在第二个 useEffect 中获取 URL 的值资本值。
    猜你喜欢
    • 2019-05-28
    • 2013-11-09
    • 1970-01-01
    • 2020-12-01
    • 2012-11-01
    • 2020-11-25
    • 2022-12-18
    • 2018-05-27
    • 2020-01-28
    相关资源
    最近更新 更多