簡體   English   中英

React API Handle Error in Fetch Call:TypeError-無法讀取未定義的屬性'temp'

[英]React API Handle Error in Fetch Call : TypeError-Cannot read property 'temp' of undefined

我正在嘗試構建一個天氣應用程序,該應用程序對於有效的城市名稱可以正常使用,但不適用於錯誤的城市名稱。

我建立了兩個模塊,第一個是App.js,第二個是Form.js,它將用戶輸入的城市名稱傳遞給App.js。

App.js是:-


import React from 'react';
import Form from './form.js';
class App extends React.Component {

  state = {
    weather:{
    temp:"",
    type:"",
    city:"",
    country:"",
    wind:"",
    humidity:""} ,
    requestSuccessfull:true
  }

  updateWeatherDetails = (area) =>{
    fetch(`http://api.openweathermap.org/data/2.5/weather?q=${area}&units=metric&APPID=b66ecf3c7e717c4eb45abd13e53ba0ac`,{mode:'cors'})
    .then((response)=>{
      return (response.json());
    })
    .then((response) =>{
      this.setState((prevState) =>({
        weather : { 
            temp:response.main.temp,
            type:response.weather[0].description,
            city:response.name,
            country:response.sys.country,
            wind:response.wind.speed,
            humidity:response.main.humidity,
        }
      }))
    })
    .catch((error) =>{
    this.setState({
    requestSuccessfull:false
   })
    console.log("error occured")

  })
}
  render(){

    if (this.state.requestSuccessfull){
      return(
      //display the weather details
      )

    }
    else{
      return(
        //display wrong city name entered by user
      )
    }
    }


}


export default App;

我不明白為什么我的catch函數沒有運行。 我還應該如何處理錯誤的API調用? 提交錯誤的城市名稱時會出現以下錯誤:

TypeError: Cannot read property 'temp' of undefined
  22 | .then((response) =>{
  23 |   this.setState((prevState) =>({
  24 |     weather : { 
> 25 |         temp:response.main.temp,
     | ^  26 |         type:response.weather[0].description,
  27 |         city:response.name,
  28 |         country:response.sys.country,

也是一個愚蠢的懷疑。 因為我附加了catch函數來處理任何錯誤,所以不應該忽略API調用上的錯誤嗎?

這是一個示例,說明如何完成此任務。.我相信使用async / await與promise比較容易理解。 跟蹤正在發生的事情比較容易。

該示例應該可以自我解釋,但是如果您有任何疑問,請告訴我。 我非常樂意提供幫助!

 class App extends React.Component { state = { weather: { temp: "", type: "", city: "", country: "", wind: "", humidity: "" }, location: "", area: "", error: "", requestSuccessfull: "" }; updateWeatherDetails = async event => { try { let area = this.state.location; let fetchUrl = `http://api.openweathermap.org/data/2.5/weather?q=${area}&units=metric&APPID=b66ecf3c7e717c4eb45abd13e53ba0ac`; let fetchOptions = { mode: "cors" }; let response = await fetch(fetchUrl, fetchOptions); let weatherData = await response.json(); let newstate = { weather: { temp: weatherData.main.temp, type: weatherData.weather[0].description, city: weatherData.name, country: weatherData.sys.country, wind: weatherData.wind.speed, humidity: weatherData.main.humidity }, location: "", requestSuccessfull: true }; this.setState(newstate); } catch (err) { this.setState(prevState => ({ ...prevState, requestSuccessfull: false, error: err, area: prevState.location, location: "" })); } }; handleLocationChange = event => { this.setState({ location: event.target.value }) } render() { return ( <div> <p>Area: {this.state.location}</p> <p style={{marginBottom:'0px'}}><small>Type a location to get weather</small></p> <input type="text" value={this.state.location} onChange={this.handleLocationChange} /> <button onClick={this.updateWeatherDetails}> Get Weather </button> {this.state.requestSuccessfull === true ? ( <div> SUCCESS <pre>{JSON.stringify(this.state.weather, null, 2)}</pre> </div> ) : this.state.requestSuccessfull === false ? ( <div> ERROR GETTING DATA FOR '{this.state.area}' ENCOUNTERED ERROR: '{ this.state.error && this.state.error.message }' </div> ) : ( "" )} </div> ); } } ReactDOM.render(<App />, document.body); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script> 

從MDN

即使響應是HTTP 404或500,從fetch()返回的Promise也不會拒絕HTTP錯誤狀態。相反,它將正常解析(ok狀態設置為false),並且僅在網絡故障或失敗時拒絕。如果有任何事情阻止了請求的完成。

解決方案是檢查狀態代碼並在必要時引發錯誤。

 fetch(`http://api.openweathermap.org/data/2.5/weather?q=${area}&units=metric&APPID=b66ecf3c7e717c4eb45abd13e53ba0ac`,{mode:'cors'})
    .then((response)=>{
        if (response.status !== 200) {
        throw new Error("Not 200 response")
       } else return (response.json());
    }).then(do stuff).catch(error => { handle error })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM