gpt4 book ai didi

reactjs - react 这是未定义的

转载 作者:行者123 更新时间:2023-12-03 13:25:32 36 4
gpt4 key购买 nike

React this 在 Promise 中未定义。这是我的代码:

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

最佳答案

可能它没有绑定(bind)this

尝试替换为 arrow functions如果你能够使用 ES6 语法。它会自动绑定(bind):

.then( (response) => {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
} )

或者手动绑定(bind):

.then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data);
}.bind(this) )

关于reactjs - react 这是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38238512/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com