我目前有一个“日期时间”组件,显示时间表示并希望更改其相对于当前时间的显示
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 实例?
最佳答案
让知道组件何时应该更新的服务发布一个事件,所有组件实例都在 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>;
}
});
关于javascript - 如何列出特定类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29877154/