this承诺中的React 未定义.这是我的代码:
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");
})
}
Run Code Online (Sandbox Code Playgroud)
这是错误代码:
TypeError: this is undefined
Stack trace:
componentDidMount/<@webpack:///./static/apps/components/Album.jsx?:81:17
Run Code Online (Sandbox Code Playgroud)
mrl*_*lew 10
可能它没有约束力this.
如果您能够使用ES6语法,请尝试使用箭头函数替换.它自动绑定这个:
.then( (response) => {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
} )
Run Code Online (Sandbox Code Playgroud)
或手动绑定:
.then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data);
}.bind(this) )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8635 次 |
| 最近记录: |