如何将火基与反应功能组件同步
我想将我的组件 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
安装
app
组件时,您可以打开快照侦听器,请参阅文档。您可以在使用
中执行此操作,还可以从使用
返回一个函数,以在组件卸下时销毁侦听器。它称为“清理功能”,请参阅react docs看起来像这样的东西:
请注意,依赖关系数组在这里是空的,这意味着它不会更改。因此,它将仅在Inital Mount上执行。
另请注意,上面的代码未测试,因此您的里程可能会有所不同。
When you mount the
App
component, you can open a snapshot listener to RTDB, see docs. You do that inuseEffect
and also return a function fromuseEffect
to destroy the listener when your component gets unmounted. It's called a "cleanup function", see React docsIt would look something like that:
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.
我在提交消息后在 AddMessage 函数中使用我的函数 writeUserData() 发送到实时数据库而不是在 UseEffect() 中,然后在刷新页面后获取消息我使用 onValue() 正如您在 UseEffect() 中所说的那样,同时我更新我的状态与 setState() ex: if (data) {
setState({消息: data.messages, 伪: state.pseudo})
} 返回
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