【问题标题】:Store geofire query results in hooks将 geofire 查询结果存储在挂钩中
【发布时间】:2020-10-13 03:20:07
【问题描述】:

您好,我遇到了 React Function useState 和 geofire。我只是想学习 hooks 和 useState,但即使努力寻找解决方案,我也无法取得任何进展。 这是我的数据库组件代码,它引发了错误

import "firebase/database";
import React, { useState } from "react";
const geofire = require("geofire");

const firebaseConfig = {
  //my config
};
firebase.initializeApp(firebaseConfig);
// const userKey = "slg3";

const firebaseRef = firebase.database().ref("users/place");
const geoFire = new geofire.GeoFire(firebaseRef);

// geoFire.set(userKey, [26.71, 88.43]).then(
//   function () {
//     console.log("Provided key has been added to GeoFire");
//   },
//   function (error) {
//     console.log("Error: " + error);
//   }
// );

let geoQuery = geoFire.query({
  center: [26.71, 88.43],
  radius: 0.001,
});

const database = () => {
  const [pos, setPos] = useState([]);
  geoQuery.on("key_entered", function (key, location, distance) {
    setPos((prev) => [...prev, location]);
    console.log(
      key +
        " entered query at " +
        location +
        " (" +
        distance +
        " km from center)"
    );
  });

  return (
    <div className="location">
      {pos.map((item) => {
        return <h1>{item}</h1>;
      })}
    </div>
  );
};
export default database;

每次从 geoQuery.on() 返回位置时,我都会尝试渲染 h1。我正在尝试将位置存储到状态变量,但我收到错误 “错误:重新渲染太多。 React 限制了渲染的数量以防止无限循环。” 我正在使用 geofire 进行查询。 请帮忙,谢谢。

【问题讨论】:

    标签: reactjs firebase react-hooks geofire


    【解决方案1】:

    我的问题已解决。我已经在 useEffect 钩子中移动了这段代码。

    初始代码:-

    geoQuery.on("key_entered", function (key, location, distance) {
        setPos((prev) => [...prev, location]);
        console.log(
          key +
            " entered query at " +
            location +
            " (" +
            distance +
            " km from center)"
        );
      });
    

    更改代码:-

    useEffect(() => { geoQuery.on("key_entered", function (key, location, distance) {
        setPos((prev) => [...prev, location]);
        console.log(
          key +
            " entered query at " +
            location +
            " (" +
            distance +
            " km from center)"
        );
      });},[]);
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2019-12-29
      • 2021-12-28
      • 1970-01-01
      相关资源
      最近更新 更多