【问题标题】:React runs an infinite loop when updating real time databaseReact 在更新实时数据库时运行无限循环
【发布时间】:2021-09-07 02:26:42
【问题描述】:
import React, { useState } from 'react';
import { ref, onValue, update} from "firebase/database";
import { database } from '../../utils/firebase';
import './Card.css';



function Card(props) {
    const [uid, setUID] = useState(props.uid);
    function completeCard() {
        const userRef = ref(database, 'users/' + uid);
          onValue(userRef, (snapshot) => {
            const data = snapshot.val();
            var completedMissions = data["challenges"];
            completedMissions.push(props.cardID);
            
            const updates = {};
            updates['/user/' + uid +'/challenges'] = completedMissions;
            //This is the line causing the infinite loop
            update(ref(database), updates);
            
          });
          
    }
    return(
        <div className="card">
            <h1>{props.name}</h1>
            <p>{props.description}</p>
            <button onClick={completeCard}>Complete</button>
            <button>+Info</button>
        </div>
    )
}
export default Card;

您好,当我尝试更新 firebase 实时数据库中的值时,会导致无限循环!我认为 onValue 可能导致问题,但我不知道如何解决它。我希望按下按钮时只更新一次值,因为它应该只更改一次,提前谢谢!

【问题讨论】:

  • 添加空依赖数组将有助于使用效果

标签: javascript reactjs firebase-realtime-database


【解决方案1】:

onValue 设置一个侦听器,该侦听器将在每次数据库的该部分更改时反复回叫您。所以它第一次获取数据并运行你的代码。您的代码会更新数据库,因此回调会再次发生,这会导致您再次更新数据库。重复。

如果您只想获取一次值,请改用get

import { ref, get, update } from "firebase/database";

//...
function completeCard() {
  const userRef = ref(database, "users/" + uid);
  get(userRef).then((snapshot) => {
    const data = snapshot.val();
    const completedMissions = data["challenges"];
    completedMissions.push(props.cardID);

    const updates = {};
    updates["/user/" + uid + "/challenges"] = completedMissions;
    update(ref(database), updates);
  });
}

或者使用异步/等待:

async function completeCard() {
  const userRef = ref(database, "users/" + uid);
  const snapshot = await get(userRef);
  const data = snapshot.val();
  const completedMissions = data["challenges"];
  completedMissions.push(props.cardID);

  const updates = {};
  updates["/user/" + uid + "/challenges"] = completedMissions;
  update(ref(database), updates);
}

【讨论】:

    猜你喜欢
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2011-05-22
    相关资源
    最近更新 更多