2016-12-02 172 views
0

我用fetch-jsonp來從darksky API的一些數據,但存儲數據時,當我獲取數據存儲數據類型錯誤在陣列

constructor(props) { 
     super(props); 
     this.state = { 
      daily: [], 
      hourly: [], 
      hourlySum: '', 
      dailySum: '', 
      loading: true, 
      error: null 
    }; 
    } 

    componentDidMount() { 
    if (navigator.geolocation){ 
     function success(position) { 

     var latitude = position.coords.latitude; 
     var longitude = position.coords.longitude; 
     var results = fetchJsonp(`https://api.darksky.net/forecast/key/`+latitude+`,`+longitude+`?units=auto`) 
     .then(result => { 
      this.setState({ 
      daily: result.daily.data, 
      hourly: result.hourly.data, 
      hourlySum: result.hourly, 
      dailySum: result.daily, 
      loading: false, 
      error: null 
      }); 
     })/*.catch(err => { 
      // Something went wrong. Save the error in state and re-render. 
      this.setState({ 
       loading: false, 
       error: err 
      }); 
      });*/ 
     }; 
     function error() { 
     console.log('geolocation error') 
     }; 
     navigator.geolocation.getCurrentPosition(success.bind(this), error); 
    } 
    } 

該錯誤消息類型錯誤時,我得到一個類型錯誤:不能讀未定義引用daily: result.daily.data財產「數據」,但因爲我定義daily爲數組我不明白爲什麼我得到一個類型錯誤 This參考

響應格式我沒有使用愛可信(這工作),但因爲同樣的事情CORS我切換到JSON P.

我的工作Axios公司代碼看起來像

var _this = this; 
    this.serverRequest = axios.get(`https://api.darksky.net/forecast/key/`+latitude+`,`+longitude+`?units=auto`) 
    .then(result => { 
     _this.setState({ 
     daily: result.data.daily.data, 
     hourly: result.data.hourly.data, 
     hourlySum: result.data.hourly, 
     dailySum: result.data.daily, 
     loading: false, 
     error: null 
     }); 
    }) 

在此先感謝

+0

呼叫前

fetchJsonp('/users.jsonp') .then(function(response) { return response.json() }).then(function(json) { console.log('parsed json', json) }).catch(function(ex) { console.log('parsing failed', ex) }) 

所以,我沒有看到你定義'daily'爲:

查看該網頁您鏈接樣品數組。你從網上獲取一些數據,看起來數據沒有一個正確的'daily'命名。基本上''result.daily'似乎是未定義的。嘗試註銷'結果'並確認您獲得了您期望的數據。 –

+0

每日數組是在構造函數中定義的。我也更新了我的問題,因爲我使用axios – frisk0

回答

1

https://github.com/camsong/fetch-jsonp網站:

Make JSONP request like window.fetch 

這意味着你將需要調用response.json(),按要求fetch。你叫setState鏈中的另一個then()一起response.json()

+0

謝謝!按預期工作:) – frisk0