2017-02-12 66 views
1

我是新來的反應,所以我敢肯定我失去了一些基本的東西。我得到這個未定義,因此不能讀取屬性'setState'試圖設置狀態在函數的返回中調用fetch,我做錯了什麼?注意我從onClick調用MyAction並且響應數據沒有問題。反應setState裏面的功能這是undefined

var ItemComponent = React.createClass({ 

getInitialState: function() { 
    return { 
    the_message: "call that API!" 
    }; 
}, 

doFetch: function() { 
    var obj = { 
    method: 'POST', 
    headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    } 
    } 
    return fetch('http://localhost:1337/site/test', obj).then(function(response) { 
    return response.json(); 
    }).then(function(data) { 
    return data; 
    }).catch((error) => { 
    console.error(error); 
    }); 
}, 

MyAction: function(){ 
    this.doFetch().then(function(response){ 
    this.setState({ 
     the_message: response.message 
    }); 
    }) 
}, 

render: function() { 
    return (
    <div> 
    <div>{this.props.title}</div><br></br> 
    <div>{this.props.price}</div><br></br> 
    <div onClick={this.MyAction}>{this.props.qty}</div> 
    </div> 
    ); 
} 

}); 
+0

可能重複[「這個」關鍵字是如何工作的?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –

回答

2

您的內在承諾解析函數將不會有this上下文。一種解決方法:

MyAction: function(){ 
    this.doFetch().then(function(response){ 
     this.setState({ 
      the_message: response.message 
     }); 
    }.bind(this)) 
}, 

瞭解更多關於this StackOverflow question

+0

Pefect,你第二次修復它,我不確定你在第一個項目中的建議是什麼,因爲這是我的代碼保持不變?無論如何,只要它讓我(5分鐘),我就會接受你的回答。旁邊的問題,我真的應該使用ES6語法是啊?在開始學習一些教程之後,我認爲這個語法很長。 – edencorbin

+0

雙哎呀,我只是假定你在使用ES6類,第一次更新是無關緊要的。請把你的問題重複一次。 –

3

使用箭頭功能() => {})它保持最後一個範圍(this)照原樣。

MyAction: function(){ 
    this.doFetch().then((response) => { 
     this.setState({ 
      the_message: response.message 
     }); 
    }); 
}, 
+0

這也適用,並顯示我一個更好的語法,真棒,謝謝分配! – edencorbin

+0

歡迎您 –

2

一個簡單.bind(this)將解決這一問題:

render: function() { 
return (
<div> 
<div>{this.props.title}</div><br></br> 
<div>{this.props.price}</div><br></br> 
<div onClick={this.MyAction.bind(this)}>{this.props.qty}</div> 
</div> 
); 

通過添加.bind(this)你保持你的函數內的範圍。