如何列出特定 class 的实例?

How to list instances of a specific class?

我目前有一个 "datetime" 组件,显示时间表示并希望更改其相对于当前时间的显示

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 实例?

您真的不应该从组件外部调用 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() });
    }
}

让知道组件何时应该更新的服务发布一个事件,所有组件实例都会在 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>;
  }
});

谢谢,我想到了这个解决方案(使用 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);