2016-01-12 47 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); 
     }); 
} 
相关问题