2016-01-12 48 views
1

我試圖使用fetch從api獲取數據。控制檯日誌是給我正確的JSON,但我發現了以下錯誤試圖設置狀態時:當設置狀態時,是什麼導致了這種TypeError?

類型錯誤:未定義無法讀取屬性「的setState」(...)

getInitialState() { 
    return { 
     checklist: {}, 
     documents: [], 
     questions: [], 
     faqs: [], 
     hospitals: [], 
     profile: {}, 
     guarantor: {}, 
    } 
}, 

componentDidMount(){ 
    this.fetchUser(1); 
    this.fetchFaqs(); 
}, 

fetchFaqs() { 
    fetch(FAQ_API) 
     .then(function(response){ 
      return response.json(); 
     }) 
     .then(function(json){ 
      console.log("faqs: " , json); 

      this.setState({ 
       faqs: json, 
      }); 

     }) 
     .catch((error) => { 
      console.warn(error); 
     }); 

}, 

回答

1

它看起來喜歡引用「這個」不再指向正確的地方,嘗試這樣做:

fetchFaqs() { 
var self = this; 
    fetch(FAQ_API) 
     .then(function(response){ 
      return response.json(); 
     }) 
     .then(function(json){ 
      console.log("faqs: " , json); 
      self.setState({ 
       faqs: json, 
      }); 
     }) 
     .catch((error) => { 
      console.warn(error); 
     }); 
} 

如果你不想創建自變量,你也可以重構你的承諾回報功能ES6脂肪箭頭函數,這將把它放在正確的範圍內:

fetchFaqs() { 
    fetch(FAQ_API) 
     .then((response) => { 
      return response.json(); 
     }) 
     .then((json) => { 
      this.setState({ 
       faqs: json, 
      }); 
     }) 
     .catch((error) => { 
      console.warn(error); 
     }); 
} 
相關問題