Reputation: 40794
I have set a simple example here: https://www.webpackbin.com/bins/-KhBJPs2jLmpQcCTSRBk
This is my class in the question:
import React, { Component, PropTypes } from 'react';
import { Redirect } from 'react-router-dom';
class RedirectMessage extends Component {
componentWillMount () {
const { timeToRedirect } = this.props;
const time = timeToRedirect || 5000;
console.log(`timer is set to ${time}`)
this.timer = setInterval(this.setoffRedirect.bind(this), time)
}
componentWillUnmount () {
clearInterval(this.timer);
}
setoffRedirect () {
console.log('setoffRedirect');
clearInterval(this.timer);
this.setState({startRedirect: true})
}
getDestination() {
const { destination } = this.props;
return destination || '/';
}
render() {
const {
message,
startRedirect
} = this.props;
console.log(`setoffRedirect >>> ${startRedirect}`);
if (startRedirect) {
return (
<Redirect to={this.getDestination()} />
)
}
return (
<div >
{message}
</div>
);
}
}
export default RedirectMessage;
What I want to achieve is to display a message before I redirect to another url
Here are the logic:
componentWillMount
setState
to set startRedirect
to truerender
if startRedirect
is true, a Redirect
tag will be rendered can cause url redirectHowever the problem is the startRedirect
remains undefined even after the timer callback is called. What have I missed?
Upvotes: 1
Views: 50
Reputation: 1318
class SomeClass extends Component {
constructor(props){
super(props);
this.state = {startRedirect: false};
}
}
The state object is not defined when using classes (es6). In cases where it is needed, you need to define it in the constructor to make it accessible.
You are also targeting startRedirect from this.props, instead of this.state within render
Upvotes: 1