簡體   English   中英

使用 Axios 從 Firestore 獲取實時數據

[英]Get realtime data from Firestore using Axios

我正在使用 Axios api 但我遇到了問題。 我在后端而不是前端只有 Firestore 調用。 我正在使用 React 和 Firestore 制作聊天應用程序,我似乎無法弄清楚如何通過 Axios 調用而不是 Firestore 來獲取連續數據。

它只更新一次,不會連續更新 stream。我必須只在前端調用 Firestore 嗎?

這是我從 redux 操作調用 axios function 的代碼。

componentDidMount() {
    this.props.getChatList();
    this.setState({
      chats: Object.values(this.props.allMessages),
    });
  }

componentDidUpdate(prevProps) {
    if (!equal(this.props.allMessages, prevProps.allMessages)) {
      this.props.getChatList();
      this.setState({
        chats: Object.values(this.props.allMessages),
      });
    }
  }

這是使用 Axios 調用的數據操作 function。

export const getChatList = () => (dispatch) => {
  dispatch({ type: "LOADING_DATA" });
  API.get("messages")
    .then((res) => {
      dispatch({
        type: "GET_MESSAGES",
        payload: res.data,
      });
    })
    .catch(() =>
      dispatch({
        type: "GET_MESSAGES",
        payload: null,
      })
    );
};

根據@ShauryaMittal 的評論,將其發布為社區 wiki。

看來這個問題與你的this.props.getChatList();有關 . 在你的componentdidmount上,它只被調用一次,所以,它只在第一次更新聊天。 您將需要一種機制來連續調用您的后端以進行聊天。

一種選擇是嘗試seetInterval()方法。 此方法 - 如此處完整解釋- 在特定時間間隔后運行一些代碼,如通過第二個參數指定的那樣。 例如,嘗試使用setInterval()連續調用后端。 componentdidmount中的setInterval(() => this.props.getChatList(), 2000)這樣每兩秒調用getChatList()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM