Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在react中使用setTimeout进行轮询_Javascript_Reactjs - Fatal编程技术网

Javascript 在react中使用setTimeout进行轮询

Javascript 在react中使用setTimeout进行轮询,javascript,reactjs,Javascript,Reactjs,为什么在这段代码中,它只运行了console.log“dostuff”两次 class Something extends React.Component { componentDidMount() { this.doStuff(); } doStuff() { console.log('do stuff') setTimeout(this.doStuff, 3000); } render() {

为什么在这段代码中,它只运行了console.log“dostuff”两次

class Something extends React.Component {
    componentDidMount() {
        this.doStuff();
    }

    doStuff() {
        console.log('do stuff')
        setTimeout(this.doStuff, 3000);
    }

    render() {
        return null
    }
}

第一次超时后,
将成为
窗口
对象,并且您在
窗口
对象上没有
doStuff
方法,因此它不会再次运行

例如,您可以将
doStuff
函数变成一个箭头函数,该函数将具有封闭词汇上下文的
this

class.com组件{
componentDidMount(){
这是doStuff();
}
多斯塔夫=()=>{
log('do stuff');
setTimeout(this.doStuff,1000);
}
render(){
返回null;
}
}
ReactDOM.render(,document.getElementById('root'))

在第一次超时后,
将成为
窗口
对象,并且您在
窗口
对象上没有
doStuff
方法,因此它将不会再次运行

例如,您可以将
doStuff
函数变成一个箭头函数,该函数将具有封闭词汇上下文的
this

class.com组件{
componentDidMount(){
这是doStuff();
}
多斯塔夫=()=>{
log('do stuff');
setTimeout(this.doStuff,1000);
}
render(){
返回null;
}
}
ReactDOM.render(,document.getElementById('root'))


您的
可能会丢失。可以尝试设置超时(this.doStuff.bind(this),3000)?您的
可能会丢失。可以尝试设置超时(this.doStuff.bind(this),3000)