ReactJS:setTimeout()不起作用?
请记住以下代码:
var Component = React.createClass({    getInitialState: function () {
        return {position: 0};    
    },
    componentDidMount: function () {
        setTimeout(this.setState({position: 1}), 3000);
    },
    render: function () {
         return (
            <div className="component">
                {this.state.position}
            </div>
         ); 
    }
});
ReactDOM.render(
    <Component />,
    document.getElementById('main')
);
难道不应该在3秒后改变状态吗?它立即改变。
我这里的主要目标是每3秒更改一次状态(使用setInterval()),但是由于它不起作用,因此我尝试了setTimeout(),它也不起作用。上面有灯吗?谢谢!
回答:
做
setTimeout(    function() {
        this.setState({ position: 1 });
    }
    .bind(this),
    3000
);
否则,您会将的结果传递setState给setTimeout。
您还可以使用箭头功能来避免使用’this’关键字:
setTimeout(    function() {
        this.setState({ position: 1 });
    }
    .bind(this),
    3000
);
否则,您会将的结果传递setState给setTimeout。
您还可以使用ES6箭头功能来避免使用this关键字:
setTimeout(  () => this.setState({ position: 1 }), 
  3000
);
以上是 ReactJS:setTimeout()不起作用? 的全部内容, 来源链接: utcz.com/qa/398319.html








