设置后无法从 reactjs 组件读取状态

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

我这里举了一个简单的例子:https://www.webpackbin.com/bins/-KhBJPs2jLmpQcCTSRBk

这是我的class问题:

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;

我想要实现的是在重定向到另一个消息之前显示一条消息url

逻辑如下:

  1. componentWillMount
  2. 中设置一个计时器
  3. 调用计时器回调时,它使用setStatestartRedirect设置为true
  4. render 中,如果 startRedirect 为真,将呈现一个 Redirect 标记,可能导致 url 重定向

然而,问题是 startRedirect 即使在调用计时器回调后仍未定义。我错过了什么?

class SomeClass extends Component {
    constructor(props){
        super(props);
        this.state = {startRedirect: false};
    }
}

使用 类 (es6) 时未定义状态对象。在需要的情况下,您需要在构造函数中定义它以使其可访问。

您还从 this.props 定位 startRedirect,而不是在 render

中定位 this.state