在我的组件的 getDefaultProps
中,我返回一个像 { id: idGenerator.unique() }
这样的对象,它应该在每个方法调用上为我提供一个唯一的 id。然而,react 不会为每个实例执行 getDefaultProps() 方法,而是只为组件执行一次。因此,每当我使用该组件时,我都会得到相同的不那么唯一 id。
是否有其他方法可以将 id 挂接到每个实例的 props 对象中?
最佳答案
props 中的状态通常是反模式,但在这里可能有意义,例如:
var Foo = React.createClass({
getInitialState: function() {
return {
id: this.props.id || idGenerator.unique()
}
}
.....
});
并且只需使用 this.state.id 而不是 props。如果组件可能在某个时刻获取 ID,您可以在 componentWillReceiveProps 中处理该问题
关于javascript - 在 getDefaultProps 中创建唯一的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29774790/