2016-04-18 14 views
8

'un o işlevinden setState ayarlanamadı durumu, fetch işlevini kullanarak aldığım promise durumundan güncelleştirmeye çalışıyorum.Promise

componentDidMount(){ 

fetch(url).then((responseText) => { 

    var response = responseText.json(); 

    response.then(function(response){ 
     this.setState(response); 
    }); 

    }); 
} 

Ben setState Sonra bir işlev

olmadığı hatayı başlamıştı, ben aşağıda gibi this değer geçmek bind(this) çalıştı.

componentDidMount(){ 

fetch(url).then((responseText) => { 

    var response = responseText.json(); 

    response.then(function(response){ 
     this.setState(response); 
    }); 

    }).bind(this); 
} 

Artık çalışmıyor. Yine aynı hata.

cevap

4

Maalesef, this değişkenini düzgün bir şekilde bağlamadığımı farkettim.

Şimdi, düzeltildi.

componentDidMount(){ 

fetch(url).then((responseText) => { 

    var response = responseText.json(); 

    response.then(function(response){ 
     this.setState(response); 
    }); 

    }.bind(this)); 
} 
+0

Bu yöntemi okunabilir durumda buluyorum. – ApertureSecurity

0

Kişisel ikinci vaadi geçerli this bağlamı yoktur. Burada bir ok işlevi de kullanabilirsiniz.

componentDidMount(){ 
    fetch(url).then((responseText) => { 
    return responseText.json(); 
    }) 
    .then((response) => { 
    this.setState(response); 
    }); 
} 

Ayrıca, yerine sizin sözünüzü yuvalanma zincirleme okunaklılık yardımcı olacak ve callback hell önlemek için yardımcı olabilir.

14

Bu, this kapsamının kapsamından kaynaklandığı için, Function.prototype.bind'u kullanmaya çalıştığınızda bir şeyleri yapıyorsunuz demektir. Hatanız, son anonim işleve sonuna kadar bağlanmadığınızdır.

componentDidMount(){ 
    fetch(url) 
     .then((responseText) => responseText.json()) 
     .then((response) => this.setState(response)); 
} 

Ok fonksiyonları daima this bağlamını tutun: Ne muhtemelen yapmak istiyorum kullanım ok fonksiyonları bu gibi tüm yoludur.