[英]Why is this arrow function not firing, and how to properly call it?
为什么someFunction
在以下代码段中没有被触发? 我收到一个错误: someFunction is not a function
。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.setInterval = this.setInterval.bind(this);
this.someFunction = this.someFunction.bind(this);
}
setInterval = () => {
console.log('Set Interval');
setTimeout(function () {
this.someFunction()
}, 2000);
}
someFunction = () => {
console.log('Some function');
}
componentDidMount() {
this.timer = this.setInterval();
}
}
因为你提到“这个”的方式是不正确的。 您可能想要使用以下选项:
选项 1:使用bind() 进行显式绑定
setInterval = () => {
setTimeout(this.someFunction.bind(this), 2000);
}
选项 2:使用粗箭头函数
setInterval = () => {
setTimeout(() => {
this.someFunction()
}, 2000);
}
这在技术上是一个范围界定问题。 someFunction
不存在,因为this
是您在传递给setTimeout
的函数中所拥有的。
可行的解决方法:
setInterval = () => {
const self = this;
setTimeout(function () {
self.someFunction()
}, 2000);
}
或使用() => { }
如下所示:
setInterval = () => {
setTimeout(() => this.someFunction(), 2000);
}
我希望这有帮助!
尝试在setInterval
使用箭头函数。
setInterval = () => {
console.log('Set Interval');
setTimeout(function () {
this.someFunction()
}, 2000);
}
可
setInterval = () => {
console.log('Set Interval');
setTimeout(() => {
this.someFunction()
}, 2000);
}
第一个片段失败,因为this
不是指正确的this
。 StackOverflow 上有很多关于这个的问题和答案,你可以搜索它们以获得更详细的解释。
someFunction 超出范围。 如果您使用箭头函数,则不需要绑定“this”。
这是组件的最简单版本。 尝试这个
class MyComponent extends React.Component {
setInterval = () => {
console.log('Set Interval');
setTimeout(this.someFunction, 2000);
}
someFunction = () => {
console.log('Some function');
}
componentDidMount() {
this.timer = this.setInterval();
}
componentWillUnmount() {
clearInterval(this.timer);
}
}
不要忘记清除 componentWillUnmount 内的计时器对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.