简体   繁体   English

React / Redux应用程序在settimeout内调度动作

[英]React / Redux app dispatching an action inside settimeout

I am trying to dispatch an action inside settimeout, but getting error. 我试图在settimeout内调度一个动作,但出现错误。 I am having this code inside a container 我在容器中有此代码

Code

setTimeout(function(){ this.props.getData(); }, 3000);

Error 错误

Uncaught TypeError: Cannot read property 'getData' of undefined

However this.props.getData(); 但是this.props.getData(); works fine outside of settimeout 在settimeout之外工作正常

this won't refer to your component class when used inside the callback function. 在回调函数中使用时, this不会引用您的组件类。 If the only thing being called by setTimeout is this.props.getData , then you don't need a new function to do that: 如果setTimeout唯一要调用的是this.props.getData ,则不需要新函数即可:

setTimeout(this.props.getData, 3000);

If you need to do additional work inside the callback function, then you can use a lambda function instead, because this will be the same as in the outer scope: 如果您需要在回调函数内部做其他工作,则可以改用lambda函数,因为this与外部作用域相同:

setTimeout(() => {
    // do something else
    this.props.getData();
}, 3000);

You have to bind this to the callback of setTimeout . 您必须this绑定到setTimeout的回调。

Like this: setTimeout(function(){ this.props.getData(); }.bind(this), 3000); 像这样: setTimeout(function(){ this.props.getData(); }.bind(this), 3000);

OR 要么

setTimeout(()=>{this.props.getData();},3000)

The this inside your setTimeout() is not the this you are expecting it to be. this你里面setTimeout()是不是this你期望的那样。 Try binding the function to your current context and see if that works. 尝试将函数绑定到当前上下文,看看是否可行。

setTimeout(function(){
   this.props.getData();
}.bind(this), 3000);

Or you can use arrow functions like so: 或者,您可以像这样使用箭头功能:

setTimeout(() => this.props.getData(), 3000);

Arrow functions are contextless. 箭头函数是无上下文的。 They inherit the parent context. 它们继承父上下文。

References: 参考文献:

Arrow functions 箭头功能

Understanding JS this 了解JS这

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM