【问题标题】:Firebase: Render list of posts created with .push in React componentFirebase:在 React 组件中渲染使用 .push 创建的帖子列表
【发布时间】:2016-10-24 10:19:32
【问题描述】:

我正在使用.push 在 Firebase 中创建一个具有唯一 ID 的对象。然后我试图通过更新组件状态在 React 组件中显示对象。

当没有唯一键时,我的组件正确显示数据(当我在 firebase 中手动创建条目作为直接子项时,但在通过 .push 创建时没有。

这是我的 react 组件渲染语句:

    class Snapshots extends React.Component {

    constructor() {
    super();
    this.state = {
      dealership: ' ',
      calls: '',
      chats: '',
      forms: '',
    };
  }

  componentDidMount() {
    const firebaseRef = firebase.database().ref().child('snapshot');
    const callsRef = firebaseRef.child('calls');
    const chatsRef = firebaseRef.child('chats');
    const formsRef = firebaseRef.child('forms');

    callsRef.on('value', snap => {
      this.setState({
        calls: snap.val()
      });
    });

    chatsRef.on('value', snap => {
      this.setState({
        chats: snap.val()
      });
    });

    formsRef.on('value', snap => {
      this.setState({
        forms: snap.val()
      });
    });
  }

    render() {
        return (<div className="container">
          <div className="row">
            <table className="table">
              <thead>
                <tr>
                  <th>Phone Calls</th>
                  <th>Live Chats</th>
                  <th>Web Forms</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td scope="row" className="phone-calls data-background"><span className="snapshot">{this.state.calls}</span></td>
                  <td className="live-chats data-background"><span className="snapshot">{this.state.chats}</span></td>
                  <td className="web-forms data-background"><span className="snapshot">{this.state.forms}</span></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
    );
    }
}

这是一个截图: http://screencast.com/t/spUuU5dDx

在我的输入字段中引用状态时,我错过了对唯一键的一些引用,但我不知道如何实际获取它。

【问题讨论】:

    标签: reactjs firebase firebase-realtime-database


    【解决方案1】:

    使用.push(),您将获得一个唯一的密钥,就像在他们的示例中一样:

    var newPostKey = firebase.database().ref('posts').push().key;
    

    然后你不能像这样设置数据:

    firebase.database().ref('posts/' + newPostKey).set({ someData: data });
    

    或者像这样:

    firebase.database().ref('posts/' + newPostKey).on('value', (data) => {
        // data.val()...
    });
    

    【讨论】:

    • 我意识到距离您的回答已经有一段时间了,但是存储 newPostKey 变量的最佳位置在哪里?假设我有一个 divs 列表,其中包含数据库中的数据,每个列表旁边都有一个复选框,并且我希望用户能够选择要删除的数据。如何将单击的复选框链接到数据库中代表的数据?
    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 2017-01-19
    • 2020-07-12
    • 1970-01-01
    • 2018-11-12
    • 2017-03-14
    • 2021-03-16
    • 1970-01-01
    相关资源
    最近更新 更多