【问题标题】:How to update Firebase data to the React application in realtime如何将 Firebase 数据实时更新到 React 应用程序
【发布时间】:2020-05-09 07:15:53
【问题描述】:

我正在开发一个将 Firebase 数据实时更新到 React 的应用程序。我想要做的是一个用户更新应用程序中的状态,同时它应该为另一个用户更新。

我已经完成了它,但它不断呈现renderStatus(),而且速度太慢。我想让它在 RDB 数据更新后更新。

class Status extends Component {
  constructor(props) {
    super(props);
    this.state = {
      to_status: false,
      from_status: false
    };
  }

  // change the state in RDB
  handleSatus = () => {
    const { post } = this.props;
    firebase
      .database()
      .ref("/busy/" + post.uid)
      .set({
        status: true,
        last_changed: firebase.database.ServerValue.TIMESTAMP
      });
    this.setState({ to_status: true });
  };

  renderStatus() {
    const { post } = this.props;
    const { to_status, from_status } = this.state;

    // fetch the data in RDB
    let self = this;
    firebase
      .database()
      .ref("/busy/" + post.uid)
      .once("value")
      .then(function(snapshot) {
        self.setState({ from_status: snapshot.val().status });
      });

      if (this.state.from_status) {
        return (
          <p>Updated</p>
        );
      } else {
        return (
          <p>Not updated yet</p>
        );
      }
  }

  render() {
    return (
      <div>
        {this.renderStatus()}
        <button onClick={this.handleStatus()}>Click!</button>
      </div>
    )
  }

【问题讨论】:

    标签: reactjs firebase firebase-realtime-database


    【解决方案1】:

    您通常希望:

    1. 在您的 componentDidMount() 方法中注册一个 on() 侦听器。
    2. 调用setState 并使用数据库中的相关数据、初始加载时间和更改时间。
    3. 让 react 照常处理来自状态的渲染。

    比如:

    componentDidMount() {
      firebase
        .database()
        .ref("/busy/" + posy.uid)
        .on("value")
        .then((snapshot) => {
          this.setState({ from_status: snapshot.val().status });
        });
    }
    render() {
      return (
        <div>
          <p>{this.state.from_status?"Updated":"Not updated yet"}</p>
          <button onClick={this.handleStatus()}>Click!</button>
        </div>
      )
    }
    

    【讨论】:

    • 非常感谢您的评论。我已将firebase(() 移至componentDidMount(),但它不能实时工作。
    猜你喜欢
    • 1970-01-01
    • 2021-03-05
    • 2017-12-20
    • 2018-06-15
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多