反应这是未定义的 [英] React this is undefined
本文介绍了反应这是未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
React this
在 promise 中是未定义的.这是我的代码:
React this
is undefined in promise . Here is my code:
export default class Album extends React.Component {
constructor(props) {
super(props);
}
componentDidMount () {
console.log(this.props.route.appState.tracks); // `this` is working
axios({
method: 'get',
url: '/api/album/' + this.props.params.id + '/' + 'tracks/',
headers: {
'Authorization': 'JWT ' + sessionStorage.getItem('token')
}
}).then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
}).catch(function (response) {
console.error(response);
//sweetAlert("Oops!", response.data, "error");
})
}
这是错误代码:
TypeError: this is undefined
Stack trace:
componentDidMount/<@webpack:///./static/apps/components/Album.jsx?:81:17
推荐答案
可能它没有绑定this
.
尝试替换为箭头函数,如果你可以使用 ES6 语法.它会自动绑定这个:
Try replacing with arrow functions if you're able to use ES6 syntax. It automatically binds this:
.then( (response) => {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
} )
或者手动绑定:
.then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data);
}.bind(this) )
这篇关于反应这是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文