Первый пример правильно привязывает значение this
(точная проблема, которую lambdas стремится решить в ES 2015).
() => this.functionNameHere()
Последние использует контекстное-значение 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");
})
}
Мы должны были бы подразделам в лямбда здесь:
.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); // 'this' isn't working
}.bind(this))
Примеры похищенные из: React this is undefined
если во втором Например, это относится к самой кнопке. Как происходит, когда страница повторно отображается, функция вызывается независимо? Должно ли this.functionNameHere() быть undefined, так как функция была определена как функция класса, а не функция кнопки? – Kelvin