我有一个类似于<UserName uid={uid}>的React组件,在其中我想使用依赖于uid的Firebase引用的值。因为属性可以改变,所以看起来我需要在componentWillMount和componentWillReceiveProps中绑定引用,如下所示:
componentWillMount() {
this.bindAsObject(userRoot.child(this.props.uid).child('name'), 'username');
},
componentWillReceiveProps(nextProps) {
this.unbind('username');
this.bindAsObject(userRoot.child(this.props.uid).child('name'), 'username');
},
render() {
return <span>{this.state.username['.value']}</span>;
},React文档warns against having state depend on props,大概是为了避免需要从两个地方更新状态。
有没有更好的方法来做这件事?
发布于 2015-09-23 07:20:49
这个看起来很好。您预计uid会发生变化并对此做出反应。
您可以考虑的一些改进:
添加uid相等性检查,以便仅在uid更改时才重新绑定
如果您需要访问其他用户属性,请创建单个包含组件,该组件绑定到整个用户数据对象并将数据作为道具向下传递:
componentWillMount() {
this.bindAsObject(userRoot.child(this.props.uid), 'user');
},
componentWillReceiveProps(nextProps) {
if (this.props.uid !== nextProps.uid) {
this.unbind('user');
this.bindAsObject(userRoot.child(this.props.uid), 'user');
}
},
render() {
return (
<div>
<UserName name={this.state.user.name}></UserName>
<Gravatar email={this.state.user.email}></Gravatar>
</div>
);
},理想情况下,您希望将所有获取/侦听代码放在一个组件中,这样较低级别的组件就不需要关心数据是如何获取的。
https://stackoverflow.com/questions/32688547
复制相似问题