P
P
PlasterTom2018-02-13 17:18:04
React
PlasterTom, 2018-02-13 17:18:04

What's wrong with the timer?

Example from tutorial:

var Timer = React.createClass({
            getInitialState: function() {
                return {
                    seconds: 0
                };
            },
            componentDidMount: function() {
                this.timer = setInterval(this.tick, 1000);
            },
            tick: function() {
                this.setState({ seconds: this.state.seconds + 1 });
            },
            componentWillUnmount: function() {
                clearInterval(this.timer);
            },
            render: function() {
                return (
                    <h4> Уже прошло {this.state.seconds} секунд </h4>
                );
            }
        });
        ReactDOM.render(
            <Timer />,
            document.getElementById('mount-point')
        );

My similar but not working (why?) example:
export default class Timer extends Component {
    
    constructor(props) {
        super(props);
        
        this.state = {
            seconds: 0
        }
    }
        
       
            componentDidMount() {
                this.timer = setInterval(this.tick, 1000);
            }
                
            tick() {
                this.setState({ seconds: this.state.seconds + 1 });
            }
        
            componentWIllUnMount() {
            clearInterval(this.timer);
            }
        
    
    
    render(){
        return(
        <h4>Уже прошло {this.state.seconds} секунд</h4>
        )
    }
}

In the console it gives an error TypeError: Cannot read property 'seconds' of undefined
at this.setState({ seconds: this.state.seconds + 1 });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Petrov, 2018-02-13
@PlasterTom

When using React.createClass, all methods in the component are automatically bound. Therefore, this is not lost there.
With ES6 classes, this no longer happens. And therefore inside tick this is already lost.
You can fix this with a simple bind:

this.timer = setInterval(this.tick.bind(this), 1000);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question