简体   繁体   English

如何正确存储来自 Firebase 实时数据库的数据并在检索到数据后使用 React 进行渲染?

[英]How to properly store data from Firebase Realtime Database and render it with React once it has been retrieved?

I am successfully retrieving data from my Firebase Realtime Database, but I am having trouble storing it and rendering it to my web page with React.我成功地从我的 Firebase 实时数据库中检索了数据,但是我在存储它并使用 React 将它渲染到我的网页时遇到了问题。 Can anyone tell me what is currently wrong with my process?谁能告诉我我的流程目前有什么问题? And/or can you share an example of 'proper' storing/rendering process in a similar use case?和/或您能否在类似的用例中分享“正确”存储/渲染过程的示例?

Here is how I am rendering stored data:这是我渲染存储数据的方式:

function Dashboard() {

var player_data;
var name_string;

return (
    <div className="dashboard">
        <h2>{player_data && player_data.settlement.settlement_name}</h2> {/* NOT RENDERING */}
    </div>

  );

And here is the function that is getting player_data that is working, which is successfully writing the data to the console:这是获取正在运行的 player_data 的函数,它成功地将数据写入控制台:

function GetPlayerData(){       
Firebase.database().ref().child("players").child(currentUser.uid).get().then((snapshot) => {
        if (snapshot.exists()) {
            console.log(snapshot.val());
            player_data = snapshot.val();
            console.log(player_data.settlement.settlement_name)
            console.log(player_data.player_data.ancestor_name)
            name_string = JSON.stringify(player_data.settlement.settlement_name)
        } else {
            console.log("No data available");
        }
        }).catch((error) => {
        console.error(error);
        });
    }

Many thanks!非常感谢!

NEXT ATTEMPT: I have attempted to store the player_data with useState as a const JSON variable as follows, and as a result am receiving "TypeError: Cannot read properties of undefined (reading 'settlement_name')"下一次尝试我尝试将带有 useState 的 player_data 存储为 const JSON 变量,如下所示,结果我收到“TypeError:无法读取未定义的属性(读取 'settlement_name')”

function Dashboard() {
const [ player_data, setPlayerData ] = useState();

return (
    <div className="dashboard">
        <h2>{player_data && player_data.settlement.settlement_name}</h2> {/* NOT RENDERING */}
        <h2>{player_data && player_data.player_data.ancestor_name}</h2> {/* NOT RENDERING */}
    </div>

And here is my updated GetPlayerData():这是我更新的 GetPlayerData():

Firebase.database().ref().child("players").child(currentUser.uid).get().then((snapshot) => {
        if (snapshot.exists()) {
            console.log(snapshot.val());
            setPlayerData(snapshot.val());
            console.log(player_data.settlement.settlement_name)
            console.log(player_data.player_data.ancestor_name)
        } else {
            console.log("No data available");
        }
        }).catch((error) => {
        console.error(error);
        });
    }

  );

Here is a screenshot of how my database is currently structured:这是我的数据库当前结构的屏幕截图: 在此处输入图片说明

Any suggestions warmly appreciated.任何建议热烈赞赏。 Thanks for reading!谢谢阅读! :) :)

WORKING CODE!:工作代码!:

function Dashboard() {
const [ playerData, setPlayerData ] = useState();

return (
    <div className="dashboard">
        <h2>{playerData && playerData.settlement.settlement_name}</h2> {/* RENDERING!! */}
        <h2>{playerData && playerData.player_data.ancestor_name}</h2> {/* RENDERING! */}
    </div>

And here is my updated GetPlayerData():这是我更新的 GetPlayerData():

Firebase.database().ref().child("players").child(currentUser.uid).get().then((snapshot) => {
        if (snapshot.exists()) {
            console.log(snapshot.val());
            setPlayerData(snapshot.val());
            console.log(playerData) {/* NOT LOGGING : RETURNING UNDEFINED */}            
            console.log(playerData.settlement.settlement_name) {/* NOT LOGGING : RETURNING TypeError: Cannot read properties of undefined (reading 'settlement') */}
        } else {
            console.log("No data available");
        }
        }).catch((error) => {
        console.error(error);
        });
    }

  );

You can use firebase API to get the data from the firebase Real-Time database and store it in a state or redux store.您可以使用 firebase API 从 firebase 实时数据库获取数据并将其存储在状态或 redux 存储中。 Use useEffect to call the async function.使用 useEffect 调用异步函数。

const getData=async ()=>{
  const response=await fetch('firebase API url');
  const data=await response.json();
  setPlayerData(data)
 }
useEffect(()=>{
 getData()
},[]);

For rendering data into JSX, let me know which type of data you are retrieving from firebase.要将数据渲染到 JSX,请告诉我您正在从 firebase 检索哪种类型的数据。 Are you returning Object or Array of Objects?你是返回对象还是对象数组?

Based on the return value we should write our code in JSX.根据返回值,我们应该在 JSX 中编写我们的代码。

If you are returning an object:如果您要返回一个对象:

const playerdata={name:'Roomba',settlement:{settlement_name:'RumCity'}}
JSX Code:
<div>
<h1>{playerData.name} {playerData.settlement.settlement_name}</h1>

If your response from firebase is an array of objects then you need to use the map function to render all the objects in UI.如果来自 firebase 的响应是一个对象数组,那么您需要使用 map 函数在 UI 中呈现所有对象。

You'll need to store the player data in the state of your component (by calling setState or a useState hook) when you get it from Firebase, so that it triggers a re-render.当您从 Firebase 获取播放器数据时,您需要将播放器数据存储在组件的状态中(通过调用setStateuseState钩子),以便触发重新渲染。 Your rendering code then can read the data from the state.然后您的渲染代码可以从状态中读取数据。

See for a pretty short example my answer here: Initiate React components with data from Firebase database?有关一个非常简短的示例,请参阅我的回答: Initiate React components with data from Firebase database? or a slightly longer one here: Retrieving items from firebase and dynamiccaly populating it in react native或者这里稍微长一点: Retrieving items from firebase and dynamiccaly populate it in react native

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 firebase 实时数据库中呈现 ScrollView React Native (expo cli) 中的数据? - How to render data in ScrollView React Native (expo cli) from firebase realtime database? 从 Firebase 数据库检索到的 Plot 数据(实时) - Plot data that retrieved from Firebase-Database (Realtime) 如何在 React 中渲染数据(实时/firebase) - How to render data (realtime/firebase) in React 如何将数据正确存储到 Firebase 实时数据库 - How to store data correctly to Firebase Realtime Database 如何在 React JS 中从 firebase 实时数据库中获取数据 - How fetch data from firebase realtime database in react js 如何在 React js 中从 firebase 实时数据库中获取数据 - how to fetch data from firebase realtime database in react js 从Firebase检索数据后,如何异步调用提取 - How do I asynchronously call fetch after data from the Firebase has been retrieved 渲染来自 firebase 实时数据库的 FlatList React Native(expo cli)中的数据? - render data in FlatList React Native (expo cli) from firebase realtime database? 如何从Firebase实时数据库中检索数据? - How to retrieve data from firebase realtime database? 从 Firebase 数据库中检索数据时,如何在 React js 中找到 state 变量的值 - How can I find a value of a state variable in React js when data is retrieved from Firebase database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM