在承诺中未定义React this
。这是我的代码:
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
答案 0 :(得分:10)
可能它没有约束this
。
如果您能够使用ES6语法,请尝试替换为arrow functions。它会自动绑定它:
.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) )
答案 1 :(得分:4)
您可以将this
绑定到thoes功能中。
或者您也在self = this
函数中声明componentDidMount
。然后在self
this
axios
的instand
答案 2 :(得分:2)
示例:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "My_Name"
};
this.componentDidMount = this.componentDidMount.bind(this);
}
componentDidMount () {
let node = this.refs.term;
term.focus();
}
render () {
return (
<div>
<input type="text" ref="term" />
</div>
);
}
}
或者您可以使用此模块auto-bind