在 getDefaultProps 中创建唯一 ID

Create unique id in getDefaultProps

在我的组件的 getDefaultProps 中,我返回一个像 { id: idGenerator.unique() } 这样的对象,它应该在每次方法调用时给我一个唯一的 ID。但是,react 不会对每个实例执行 getDefaultProps() 方法,而是对组件只执行一次。因此,每当我使用该组件时,我都会得到相同的 not-so-unique id。

是否有替代方法将 id 挂接到每个实例的 props 对象中?

state from props 通常是反模式,但在这里可能有意义,例如:

var Foo = React.createClass({
   getInitialState: function() {
       return {
           id: this.props.id || idGenerator.unique()
       }
   }
   .....
});

并且只使用 this.state.id 而不是道具。如果组件可能在某个时候获得 ID,您可以在 componentWillReceiveProps

中处理它