ReactJS: setTimeout() not working?
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')
);
setTimeout(() => {
this.setState({ position: 1 });
}, 3000);
The above would also work because the ES6 arrow function does not change the context of this
.
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
);