有人可以解释一下两者之间的区别吗
匿名函数
<button onClick={() => this.functionNameHere()}></button>
and
调用如下函数
<button onClick={this.functionNameHere()}></button>
以及何时使用其中一种(例如在不同的场景中使用其中一种)。
第一个示例正确绑定了值this
(这正是 lambda 在 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");
})
}
我们需要在这里使用 lambda:
.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) )
窃取的示例:反应这是未定义的 https://stackoverflow.com/questions/38238512/react-this-is-undefined
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)