ReactJS: setTimeout() not working?

前端 未结 10 2179

Having this code in mind:

var Component = React.createClass({

    getInitialState: function () {
        return {position: 0};    
    },

    componentDid         


        
相关标签:
10条回答
  • 2020-12-04 08:00

    You did syntax declaration error, use proper setTimeout declaration

    message:() => { 
      setTimeout(() => {this.setState({opened:false})},3000); 
      return 'Thanks for your time, have a nice day                                                                     
    0 讨论(0)
  • 2020-12-04 08:05

    setState is being invoked immediately due to the parenthesis! Wrap it in an anonymous function, then call it:

    setTimeout(function() {
        this.setState({position: 1})
    }.bind(this), 3000);
    
    0 讨论(0)
  • 2020-12-04 08:06

    Anytime we create a timeout we should s clear it on componentWillUnmount, if it hasn't fired yet.

          let myVar;
             const Component = React.createClass({
    
                getInitialState: function () {
                    return {position: 0};    
                },
    
                componentDidMount: function () {
                     myVar = setTimeout(()=> this.setState({position: 1}), 3000)
                },
    
                componentWillUnmount: () => {
                  clearTimeout(myVar);
                 };
                render: function () {
                     return (
                        <div className="component">
                            {this.state.position}
                        </div>
                     ); 
                }
    
            });
    
    ReactDOM.render(
        <Component />,
        document.getElementById('main')
    );
    
    0 讨论(0)
  • 2020-12-04 08:16

    Do

    setTimeout(
        function() {
            this.setState({ position: 1 });
        }
        .bind(this),
        3000
    );
    

    Otherwise, you are passing the result of setState to setTimeout.

    You can also use ES6 arrow functions to avoid the use of this keyword:

    setTimeout(
      () => this.setState({ position: 1 }), 
      3000
    );
    
    0 讨论(0)
提交回复
热议问题