2015-04-26 50 views
3

我现在有一个“日期时间”组件,显示时间表示,并希望其显示相对改变到当前时间如何列出特定类的实例?

var MDate = React.createClass({ 
    render: function() { 
     // this.props.date is an integer 
     var d = new Date(this.props.date); 
     var diff = ((new Date() - d)/1000) | 0; 

     return <time>{diff} seconds ago</time>; 
    } 
}); 

(注意,这是一个简化的例子,实际的代码改变格式取决于差异)

我想定期刷新该组件的每个实例的组件值,但似乎React没有提供这样做的方式。

到目前为止,我已经想出了这一点,但是这似乎很不理想:

var MDate = React.createClass({ 
    componentWillMount: function() { 
     MDate.items.push(this); 
    }, 
    componentWillUnmount: function() { 
     var i = MDate.items.indexOf(this); 
     if (i > -1) { 
      MDate.items.splice(i, 1); 
     }   
    }, 
    render: function() { … } 
} 

MDate.items = []; 

然后在MDate.items迭代,并调用forceUpdate()为每一个

有没有一种方式列出MDate的每个已安装实例而不依赖此技巧?

回答

1

做,知道当组件应更新发布,所有的组件实例监听在componentDidMount事件的服务。在该事件监听器中,您可以调用setState触发组件重新渲染。

事情是这样的:

let MDate = React.createClass({ 
    getInitialState() { 
    return this.getState(); 
    }, 
    getState() { 
    return { 
     date: DateStore.get() 
    }; 
    }, 
    componentDidMount() { 
    DateStore.on('change',() => this.setState(this.getState())); 
    }, 
    render() { 
    let d = new Date(this.state.date); 
    let diff = ((new Date() - d)/1000) | 0; 

    return <time>{diff} seconds ago</time>; 
    } 
}); 
0

您不应该从组件外部真正地调用forceUpdatesetState。这是做这件事:

var MDate = React.createClass({ 
    componentWillMount: function() { 
     this._timer = setInterval(this.update, 1000); 
    }, 
    componentWillUnmount: function() { 
     clearInterval(this._timer); 
    }, 
    getInitialState() { 
     return { 
      currentDate: new Date() 
     }; 
    }, 
    render: function() { 
     // this.props.date is an integer 
     var d = new Date(this.props.date); 
     var diff = ((this.state.currentDate - d)/1000) | 0; 

     return <time>{diff} seconds ago</time>; 
    }, 
    update() { 
     this.setState({ currentDate: new Date() }); 
    } 
} 
0

谢谢你,我想出了这个解决方案(使用jQuery作弊)

var MDate = React.createClass({ 
    getInitialState: function() { 
     return {tick: new Date().getTime()}; 
    }, 
    tick: function(ev) { 
     this.setState({tick: ev.timeStamp}) 
    }, 
    componentWillMount: function() { 
     $(document).on('date-tick', this.tick); 
    }, 
    componentWillUnmount: function() { 
     $(document).off('date-tick', this.tick); 
    }, 
    render: function() {…} 
} 

window.setInterval(function() { 
    $(document).trigger('date-tick') 
}, 20 * 1000); 
相关问题