Anthony Kong
Anthony Kong

Reputation: 40794

Unable to read a state from a reactjs component after it is set

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:

  1. set up a timer in componentWillMount
  2. When the timer callback is called, it uses setState to set startRedirect to true
  3. In render if startRedirect is true, a Redirect tag will be rendered can cause url redirect

However the problem is the startRedirect remains undefined even after the timer callback is called. What have I missed?

Upvotes: 1

Views: 50

Answers (1)

thsorens
thsorens

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

Related Questions