在ReactFire中,如何绑定依赖于属性的ref?

时间:2015-09-21 06:20:16

标签: reactjs firebase

我有一个像<UserName uid={uid}>一样使用的React组件,其中我想使用依赖于uid的Firebase引用的值。由于道具可以改变,看起来我需要在componentWillMountcomponentWillReceiveProps中绑定引用,如:

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,大概是为了避免从两个地方更新状态的确切需要。

有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

看起来很好。您预计uid会改变并对其作出反应。

您可以考虑进行一些改进:

添加uid等式检查,以便仅在uid更改时重新绑定

如果您需要访问其他用户属性,请创建一个包含绑定到整个用户数据对象的组件,并将数据作为props传递下去:

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>
  );
},

理想情况下,您希望将所有提取/侦听代码放在一个组件中,以便较低级别的组件不需要关心如何获取数据。