【问题标题】:Get realtime data from Firestore using Axios使用 Axios 从 Firestore 获取实时数据
【发布时间】:2020-07-28 18:37:16
【问题描述】:

我正在使用 Axios api,但遇到了问题。我只有在后端而不是前端有 Firestore 调用。我正在使用 React 和 Firestore 制作聊天应用程序,但我似乎无法弄清楚如何通过 Axios 调用而不是 Firestore 来获取连续数据。

它只更新一次,不会连续流式传输。我必须在前端调用 Firestore 吗?

这是我从 redux 操作中调用 axios 函数的代码。

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 调用的数据动作函数。

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

【问题讨论】:

  • 这是因为componentdidmount 中的this.props.getChatList(); 只被调用一次,并且它会第一次更新聊天。您将需要一种机制来持续调用您的后端以获取聊天记录。尝试使用 setInterval 连续调用后端。 componentdidmount 中的 setInterval(() => this.props.getChatList(), 2000) 之类的东西,以便每两秒调用一次 getChatList()

标签: node.js reactjs redux google-cloud-firestore axios


【解决方案1】:

根据@ShauryaMittal 评论将其发布为社区维基。

问题似乎与您的this.props.getChatList(); 有关。在你的componentdidmount'上,它只被调用一次,所以,它只会在第一次更新聊天。您将需要一种机制来持续调用您的后端以获取聊天记录。

一种选择是尝试seetInterval() 方法。此方法 - 正如here 的完整解释 - 在特定时间间隔后运行一些代码,如通过第二个参数指定的那样。例如,尝试使用setInterval() 连续调用后端。 componentdidmount 中的 setInterval(() => this.props.getChatList(), 2000) 之类的东西,这样每两秒就会调用一次 getChatList()

【讨论】:

  • 这不会导致对 Firestore 的大量读取吗?
  • 嗨@EnglishBanana,如果您想从 Firestore 数据库中获取连续数据,您将获得更多的阅读量。此解决方案是可以做什么的一个示例,但请记住,您将实施以获取更新和检索数据的任何方式都会增加读取次数。当然,您可以随时提高函数运行的时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 2021-03-04
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
相关资源
最近更新 更多