如何将火基与反应功能组件同步

发布于 2025-01-17 11:56:59 字数 1915 浏览 0 评论 0原文

我想将我的组件 React 与 Firebase 同步,但我使用一个功能组件,我在互联网上找到了一些答案,但它看起来很复杂,对我不起作用 我不能使用这个: useEffect(() => { base.syncState('/', { context: this, state: 'messages' }) });

我的代码是

import React,{useEffect, useState} from 'react'
import Formulaire from './component/Formulaire'
import Message from './component/Message'
import {useParams} from 'react-router-dom'
import database from './Base'
import { getDatabase, ref, set,onValue } from "firebase/database";

function App() {
  const [state , setState] = useState({
    messages : {},
    pseudo : useParams().pseudo,
  })
  const addMessage = (message) =>{
    state.messages[`message-${Date.now()}`] = message
    setState({pseudo : state.pseudo ,messages : state.messages})
  }

    const msg = Object.keys(state.messages)
    const lastMessages = msg.map(key=>{
      return <Message key={key} pseudo={state.messages[key].pseudo} message = {state.messages[key].message} />
    })
  return (
    <div className="container-lg col-4 mt-5">
      <div>
        {lastMessages}
      </div>
      <Formulaire length={150} addMessage ={addMessage} pseudo={state.pseudo} />
    </div>
  )
}



export default App

我的 firebaseApp 代码:

import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";

// TODO: Replace with your app's Firebase project configuration
const firebaseConfig = {
  apiKey: "AIzaSyB2CFjr32PoNdsnfvEgt_AijgE18lNKz2c",
  authDomain: "chat-app-42ed5.firebaseapp.com",
  projectId: "chat-app-42ed5",
  storageBucket: "chat-app-42ed5.appspot.com",
  messagingSenderId: "880643875911",
  appId: "1:880643875911:web:9d04114b45bb40c2627d62",
  measurementId: "G-MP1VZCGRDP"
};

const app = initializeApp(firebaseConfig);

// Get a reference to the database service
const database = getDatabase(app);

export default database

I would like to sync my component React with Firebase but i use a functional component i found somes answers in internet but it's seems complicated and doesn't worked for me
and i can't use this : useEffect(() => { base.syncState('/', { context: this, state: 'messages' }) });

my code is

import React,{useEffect, useState} from 'react'
import Formulaire from './component/Formulaire'
import Message from './component/Message'
import {useParams} from 'react-router-dom'
import database from './Base'
import { getDatabase, ref, set,onValue } from "firebase/database";

function App() {
  const [state , setState] = useState({
    messages : {},
    pseudo : useParams().pseudo,
  })
  const addMessage = (message) =>{
    state.messages[`message-${Date.now()}`] = message
    setState({pseudo : state.pseudo ,messages : state.messages})
  }

    const msg = Object.keys(state.messages)
    const lastMessages = msg.map(key=>{
      return <Message key={key} pseudo={state.messages[key].pseudo} message = {state.messages[key].message} />
    })
  return (
    <div className="container-lg col-4 mt-5">
      <div>
        {lastMessages}
      </div>
      <Formulaire length={150} addMessage ={addMessage} pseudo={state.pseudo} />
    </div>
  )
}



export default App

And my firebaseApp code :

import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";

// TODO: Replace with your app's Firebase project configuration
const firebaseConfig = {
  apiKey: "AIzaSyB2CFjr32PoNdsnfvEgt_AijgE18lNKz2c",
  authDomain: "chat-app-42ed5.firebaseapp.com",
  projectId: "chat-app-42ed5",
  storageBucket: "chat-app-42ed5.appspot.com",
  messagingSenderId: "880643875911",
  appId: "1:880643875911:web:9d04114b45bb40c2627d62",
  measurementId: "G-MP1VZCGRDP"
};

const app = initializeApp(firebaseConfig);

// Get a reference to the database service
const database = getDatabase(app);

export default database

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

闻呓 2025-01-24 11:56:59

安装app组件时,您可以打开快照侦听器,请参阅文档。您可以在使用中执行此操作,还可以从使用返回一个函数,以在组件卸下时销毁侦听器。它称为“清理功能”,请参阅react docs

看起来像这样的东西:

function App() {
 useEffect(() => {
    const unsubListener = onValue(ref(rtdb_instance, '/YOUR_PATH'), (snapshot) => {
      // Probably iterate over `snapshot.val()` and store it in your state
    })

    // Return cleanup function
    return unsubListener;
 }, [])
}

请注意,依赖关系数组在这里是空的,这意味着它不会更改。因此,它将仅在Inital Mount上执行。

另请注意,上面的代码未测试,因此您的里程可能会有所不同。

When you mount the App component, you can open a snapshot listener to RTDB, see docs. You do that in useEffect and also return a function from useEffect to destroy the listener when your component gets unmounted. It's called a "cleanup function", see React docs

It would look something like that:

function App() {
 useEffect(() => {
    const unsubListener = onValue(ref(rtdb_instance, '/YOUR_PATH'), (snapshot) => {
      // Probably iterate over `snapshot.val()` and store it in your state
    })

    // Return cleanup function
    return unsubListener;
 }, [])
}

Note that the dependency array is empty here, meaning it won't change. Hence, it will only be executed on inital mount.

Also please note that the code above is not tested, so your milage might vary.

紫瑟鸿黎 2025-01-24 11:56:59

我在提交消息后在 AddMessage 函数中使用我的函数 writeUserData() 发送到实时数据库而不是在 UseEffect() 中,然后在刷新页面后获取消息我使用 onValue() 正如您在 UseEffect() 中所说的那样,同时我更新我的状态与 setState() ex: if (data) {
setState({消息: data.messages, 伪: state.pseudo})
} 返回

import React,{useState,useEffect} from 'react'
import Formulaire from './component/Formulaire'
import Message from './component/Message'
import {useParams} from 'react-router-dom'
import database from './Base'
import { ref, set,onValue } from "firebase/database";

function App() {

  const [state , setState] = useState({
    messages : {},
    pseudo : useParams().pseudo,
  })
  
  useEffect(()=>{
  const resultDb = ref(database);
  onValue(resultDb, (snapshot) => {
  const data = snapshot.val();
  if (data) {
    setState({messages : data.messages , pseudo : state.pseudo})
  } return 
})
   return resultDb
  },[])

  function writeUserData(message) {
    set(ref(database), {
      messages :message
    });
  }

  const addMessage = (message) =>{
    state.messages[`message-${Date.now()}`] = message
    setState({pseudo : state.pseudo ,messages : state.messages})
    writeUserData(state.messages)
  }

  const msg = Object.keys(state.messages)
  const lastMessages = msg.map(key=>{
    return <Message key={key} pseudo={state.messages[key].pseudo} message = {state.messages[key].message} />
    })
  return (
    <div className="container-lg col-4 mt-5">
      <div>
        {lastMessages}
      </div>
      <Formulaire length={150} addMessage ={addMessage} pseudo={state.pseudo} />
    </div>
  )
}

export default App

I use my function writeUserData() in AddMessage function after submit message to send to REALTIME DATABASE not in UseEffect() and after to get message after refresh page i use onValue() as you say in UseEffect() and in the same time i update my state with setState() ex: if (data) {
setState({messages : data.messages , pseudo : state.pseudo})
} return

import React,{useState,useEffect} from 'react'
import Formulaire from './component/Formulaire'
import Message from './component/Message'
import {useParams} from 'react-router-dom'
import database from './Base'
import { ref, set,onValue } from "firebase/database";

function App() {

  const [state , setState] = useState({
    messages : {},
    pseudo : useParams().pseudo,
  })
  
  useEffect(()=>{
  const resultDb = ref(database);
  onValue(resultDb, (snapshot) => {
  const data = snapshot.val();
  if (data) {
    setState({messages : data.messages , pseudo : state.pseudo})
  } return 
})
   return resultDb
  },[])

  function writeUserData(message) {
    set(ref(database), {
      messages :message
    });
  }

  const addMessage = (message) =>{
    state.messages[`message-${Date.now()}`] = message
    setState({pseudo : state.pseudo ,messages : state.messages})
    writeUserData(state.messages)
  }

  const msg = Object.keys(state.messages)
  const lastMessages = msg.map(key=>{
    return <Message key={key} pseudo={state.messages[key].pseudo} message = {state.messages[key].message} />
    })
  return (
    <div className="container-lg col-4 mt-5">
      <div>
        {lastMessages}
      </div>
      <Formulaire length={150} addMessage ={addMessage} pseudo={state.pseudo} />
    </div>
  )
}

export default App
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文