从 Firebase 实时数据库中删除单个项目时出现问题。反应本机

问题描述 投票:0回答:1

我尝试构建一个移动应用程序,您可以在其中创建团队和玩家。并将其保存到数据库中。我能够做到这一点,但是当我尝试为单人游戏创建删除功能时遇到问题。我可以删除整个团队,这很有效,但我无法删除单个玩家。这个问题的底部是我的数据库。

这是我在数据库中创建团队的方法:

const createTeam = async () => {
     const userTeamRef = ref(database, 'users/' + userId + '/teams');
     const newTeamRef = push(userTeamRef);
     const newTeamKey = newTeamRef.key;
 
     
     const teamID = newTeamKey;
 
     const teamRef = ref(database, 'teams/' + teamID);
     const newTeam = {
         teamID: teamID, 
         name: teamName,
         players: players.map(player => ({
             playerID: player.playerID,
             name: player.name,
             stats: playerStats[player.playerID] || {
                 plus: false,
                 minus: false,
                 shot: false,
                 shotOnGoal: false
             }
         })),
     };
     try {
         await set(teamRef, newTeam);
         console.log('New team created successfully!');
     } catch (error) {
         console.error('Error creating new team:', error);
     }
 };
 

 const addPlayer = () => {
     const playerID = push(ref(database, 'players')).key; 
     setPlayers([...players, { name: playerName, playerID }]); 
     setPlayerStats(prevState => ({
         ...prevState,
         [playerID]: { 
             name: playerName,
             plus: false,
             minus: false,
             shot: false,
             shotOnGoal: false
         }
     }));
     setPlayerName('');
 };

这是从其他组件中删除方法:

useEffect(() => {
 const teamsRef = ref(database, 'teams');
 onValue(teamsRef, (snapshot) => {
   const data = snapshot.val();
   if (data) {
     const teamsArray = Object.values(data);
     setTeams(teamsArray);
   }
 });

 return () => {
   
 };
 }, []);

 useEffect(() => {
 if (selectedTeam) {
   setPlayers(selectedTeam.players); 
 } else {
   setPlayers([]); 
 }
 }, [selectedTeam]);

 const handleDeletePlayer = (playerID) => {
 console.log("Deleting player", playerID);

 if (selectedTeam) {
   const teamRef = ref(database, `teams/${selectedTeam.teamID}/players/${playerID}`);
   console.log(teamRef);
   remove(teamRef)
     .then(() => {
       console.log(playerID, 'successful removed');
       
       setPlayers(prevPlayers => prevPlayers.filter(player => player.playerID != playerID));
       console.log(players);
     })
     .catch((error) => {
       console.error('Error removing player:', error);
     });
 }
};

 const handleDeleteTeam = () => {
  if (selectedTeam) {
    const teamRef = ref(database, `teams/${selectedTeam.teamID}`);
   remove(teamRef)
     .then(() => {
       console.log(selectedTeam.teamID, 'successful removed');
       setPlayers([]);
       setSelectedTeam(null);
     })
     .catch((error) => {
       console.error('Error removing team:', error);
     });
  }
 };

如果我写得正确,这里是数据库:

{
  "-NvajG9MkZFjZXgrAn-E": {
   "name": "Canada",
  "players": [
  {
    "0": {
      "name": "Sidney Crosby",
      "playerID": "-NvajBsvVwe7bJ6kbXXh",
      "stats": {}
    }
  },
  {
    "1": {
      "name": "Connor McDavid",
      "playerID": "-NvajFnxRRfc74Vg7Ysu",
      "stats": {}
    }
  }
],
"teamID": "-NvajG9MkZFjZXgrAn-E"
}
}
javascript firebase react-native firebase-realtime-database
1个回答
0
投票

您从团队中删除球员的代码与您的数据结构不匹配。代码:

ref(database, `teams/${selectedTeam.teamID}/players/${playerID}`);

数据结构:

{
  "-NvajG9MkZFjZXgrAn-E": {
   "name": "Canada",
  "players": [
  {
    "0": {
      "name": "Sidney Crosby",
      "playerID": "-NvajBsvVwe7bJ6kbXXh",
      "stats": {}
    }
  },

如果

playerID
"0"
,这就会起作用,但我的猜测是它实际上是
"-NvajBsvVwe7bJ6kbXXh"

当前数据结构中您唯一的选择是:

  1. 加载整个团队
  2. 从 JavaScript 代码中的
    players
    数组中删除播放器(例如使用
    filter
  3. 将整个数组写回数据库

虽然上述方法可行,但并不理想。更好的方法是更改数据结构以更好地匹配用例:

"players": {
  "-NvajBsvVwe7bJ6kbXXh": {
    "name": "Sidney Crosby",
    "stats": {}
  }
  "-NvajFnxRRfc74Vg7Ysu": {
    "name": "Connor McDavid",
    "stats": {}
  }
}

所以现在

players
不再是一个数组,而是一组键值 - 其中每个键都是玩家的 ID。这样做的优点是每个玩家(根据定义)只能在团队中出现一次。

使用新的数据结构,当前删除玩家的代码实际上可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.