简体   繁体   中英

What is the right way to assign element of an array to state using React hooks?

I'm making simple weather app based on api

In the beggining of functional component I declare this

   const [pressure, setPressure] = useState("")
   const [hourTemp, setHourTemp] = useState([])

Then I download data object from api using fetch() and assign values to state. Pressure(for example) is a single value, but in my app I need hourly forecast so I take whole hourly array and filter it (it has 48 hours and I only need 10).

    setPressure(data.current.pressure)
    let newArray = data.hourly.filter(a => {
       return data.hourly.indexOf(a) < 10
    })

After newArray is created I can console.log 在此处输入图像描述 it and it prints array of 10 objects exactly how I want it.

But when I assign this array to state

setHourTemp(newArray) 

and then pass an element as props, it returns undefined

 <WeatherBlock temp={hourTemp[0].temp}/> //TypeError: hourTemp[0] is undefined

Try adding a empty/null validation to check if your array is valid.

There are many ways to do that, but to test:

{hourTemp ? <WeatherBlock temp={hourTemp[0].temp}/> : <></> }

Because you are using fetch which is an async function, it need time to load the data. When the first time you call / render hourTemp[0] , the data still empty, and it returns error undefined. So you need to validate if the data is exist or not. There are many ways to do this:

  1. Using ternary expression
<WeatherBlock temp={hourTemp[0] ? hourTemp[0].temp : 0}/> 
  1. Using conditional rendering, you use if else before the return
    if(hourTemp[0]){
      return <WeatherBlock temp={hourTemp[0].temp}/> 
    } else {
      return <WeatherBlock temp={0}/> 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM