2017-04-08 73 views
1

我已经在这里设置一个简单的例子:https://www.webpackbin.com/bins/-KhBJPs2jLmpQcCTSRBk无法从reactjs组件读取的状态设置完成后

这是我在这个问题类:

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. 当计时器回调被调用,它使用setState设置startRedirect为true
  3. render如果startRedirect是真实的,一个Redirect标签将呈现可导致URL重定向

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

+0

国家将在你的情况是不确定的,如果你的类中创建一个构造函数,并设置this.state = {},那么你可以访问状态对象。 – thsorens

+2

你正在设置状态变量'startRedirect'和里面的渲染方法,你试图从道具上读取'startRedirect'。 –

回答

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

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

您也从this.props瞄准startRedirect,而不是this.state内作出

+0

所以你的意思是'if(this.state.startRedirect){'? –

+0

在您的示例中,您的目标是this.props.startRedirect,而不是this.state.startRedirect。 – thsorens