3 回答

TA貢獻(xiàn)1775條經(jīng)驗 獲得超11個贊
還綁定回調(diào)函數(shù),以便this回調(diào)內(nèi)部指向React Component的上下文,而不是回調(diào)函數(shù)
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: (data) => {
this.setState( { posts: data } )
}
});
}
或者你可以像這樣使用bind
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
this.setState({ posts: data })
}.bind(this)
});
}

TA貢獻(xiàn)1863條經(jīng)驗 獲得超2個贊
這個問題與失去的環(huán)境相關(guān)的這個。請嘗試以下方法:
let self = this;
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
self.setState( { posts: data } )
}
});
}
或者您可以使用bind:
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
self.setState( { posts: data } )
}
});
}.bind(this)

TA貢獻(xiàn)1813條經(jīng)驗 獲得超2個贊
您必須將上下文存儲到變量中,因為“ this”引用在回調(diào)中將不可用。請嘗試以下解決方案:
getPosts = () => {
let that=this;
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
that.setState( { posts: data } )
}
});
}
分享編輯
添加回答
舉報