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) 我是 React 初学者。在学习React的过程中,有时会看到有人在事件监听器中使用匿名函数,不知道下面的代码是不是一样。我认为,要调用函数 onDelete,我们只需要使用 onClick={this.onDelete(id)}
const cartItem=this.props.cart.map((bookCart)=>{
return (
<Button onClick={()=>{this.onDelete(bookCart._id)}}>Delete</Button>
)
},this;
Run Code Online (Sandbox Code Playgroud)
和
const cartItem=this.props.cart.map((bookCart)=>{
return (
<Button onClick={this.onDelete(bookCart._id)}>Delete</Button>
)
},this;
Run Code Online (Sandbox Code Playgroud)