- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图弄清楚如何使用Firebase侦听器,以便使用react hooks更新来刷新云Firestore数据。
最初,我使用带有componentDidMount函数的类组件来获取Firestore数据。
this.props.firebase.db
.collection('users')
// .doc(this.props.firebase.db.collection('users').doc(this.props.firebase.authUser.uid))
.doc(this.props.firebase.db.collection('users').doc(this.props.authUser.uid))
.get()
.then(doc => {
this.setState({ name: doc.data().name });
// loading: false,
});
}
import React, { useState, useEffect } from 'react';
import { useDocument } from 'react-firebase-hooks/firestore';
import {
BrowserRouter as Router,
Route,
Link,
Switch,
useRouteMatch,
} from 'react-router-dom';
import * as ROUTES from '../../constants/Routes';
import { compose } from 'recompose';
import { withFirebase } from '../Firebase/Index';
import { AuthUserContext, withAuthorization, withEmailVerification, withAuthentication } from '../Session/Index';
function Dashboard2(authUser) {
const FirestoreDocument = () => {
const [value, loading, error] = useDocument(
Firebase.db.doc(authUser.uid),
//firebase.db.doc(authUser.uid),
//firebase.firestore.doc(authUser.uid),
{
snapshotListenOptions: { includeMetadataChanges: true },
}
);
return (
<div>
<p>
{error && <strong>Error: {JSON.stringify(error)}</strong>}
{loading && <span>Document: Loading...</span>}
{value && <span>Document: {JSON.stringify(value.data())}</span>}
</p>
</div>
);
}
}
export default withAuthentication(Dashboard2);
<Route path={ROUTES.DASHBOARD2} render={props => (
<AuthUserContext.Consumer>
{ authUser => (
<Dashboard2 authUser={authUser} {...props} />
)}
</AuthUserContext.Consumer>
)} />
class Firebase {
constructor() {
app.initializeApp(config).firestore();
/* helpers */
this.fieldValue = app.firestore.FieldValue;
/* Firebase APIs */
this.auth = app.auth();
this.db = app.firestore();
}
onAuthUserListener(next, fallback) {
// onUserDataListener(next, fallback) {
return this.auth.onAuthStateChanged(authUser => {
if (authUser) {
this.user(authUser.uid)
.get()
.then(snapshot => {
let snapshotData = snapshot.data();
let userData = {
...snapshotData, // snapshotData first so it doesn't override information from authUser object
uid: authUser.uid,
email: authUser.email,
emailVerified: authUser.emailVerifed,
providerData: authUser.providerData
};
setTimeout(() => next(userData), 0); // escapes this Promise's error handler
})
.catch(err => {
// TODO: Handle error?
console.error('An error occured -> ', err.code ? err.code + ': ' + err.message : (err.message || err));
setTimeout(fallback, 0); // escapes this Promise's error handler
});
};
if (!authUser) {
// user not logged in, call fallback handler
fallback();
return;
}
});
};
import FirebaseContext, { withFirebase } from './Context';
import Firebase from '../../firebase';
export default Firebase;
export { FirebaseContext, withFirebase };
import React from 'react';
const FirebaseContext = React.createContext(null);
export const withFirebase = Component => props => (
<FirebaseContext.Consumer>
{firebase => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
export default FirebaseContext;
import React from 'react';
import { AuthUserContext } from '../Session/Index';
import { withFirebase } from '../Firebase/Index';
const withAuthentication = Component => {
class WithAuthentication extends React.Component {
constructor(props) {
super(props);
this.state = {
authUser: null,
};
}
componentDidMount() {
this.listener = this.props.firebase.auth.onAuthStateChanged(
authUser => {
authUser
? this.setState({ authUser })
: this.setState({ authUser: null });
},
);
}
componentWillUnmount() {
this.listener();
};
render() {
return (
<AuthUserContext.Provider value={this.state.authUser}>
<Component {...this.props} />
</AuthUserContext.Provider>
);
}
}
return withFirebase(WithAuthentication);
};
export default withAuthentication;
Firebase' is not defined
import React, { useEffect, useContext } from 'react';
import Firebase from '../../firebase';
export const userContext = React.createContext({
user: null,
})
export const useSession = () => {
const { user } = useContext(userContext)
return user
}
export const useAuth = () => {
const [state, setState] = React.useState(() =>
{ const user = firebase.auth().currentUser
return { initializing: !user, user, }
}
);
function onChange(user) {
setState({ initializing: false, user })
}
React.useEffect(() => {
// listen for auth state changes
const unsubscribe = firebase.auth().onAuthStateChanged(onChange)
// unsubscribe to the listener when unmounting
return () => unsubscribe()
}, [])
return state
}
function App() {
const { initializing, user } = useAuth()
if (initializing) {
return <div>Loading</div>
}
// )
// }
// const App = () => (
return (
<userContext.Provider value={{ user }}>
<Router>
<Navigation />
<Route path={ROUTES.LANDING} exact component={StandardLanding} />
TypeError: _firebase__WEBPACK_IMPORTED_MODULE_2__.default.auth is not a function
const FirebaseContext = React.createContext();
export const FirebaseProvider = (props) => (
<FirebaseContext.Provider value={new Firebase()}>
{props.children}
</FirebaseContext.Provider>
);
import React, { useEffect, useContext, useState } from 'react';
const useFirebaseAuthentication = (firebase) => {
const [authUser, setAuthUser] = useState(null);
useEffect(() =>{
const unlisten =
firebase.auth.onAuthStateChanged(
authUser => {
authUser
? setAuthUser(authUser)
: setAuthUser(null);
},
);
return () => {
unlisten();
}
});
return authUser
}
export default useFirebaseAuthentication;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App/Index';
import {FirebaseProvider} from './components/Firebase/ContextHookProvider';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<FirebaseProvider>
<App />
</FirebaseProvider>,
document.getElementById('root')
);
serviceWorker.unregister();
import React, {useContext} from 'react';
import { FirebaseContext } from '../Firebase/ContextHookProvider';
import useFirebaseAuthentication from '../Firebase/ContextHook';
const Dashboard2 = (props) => {
const firebase = useContext(FirebaseContext);
const authUser =
useFirebaseAuthentication(firebase);
return (
<div>authUser.email</div>
)
}
export default Dashboard2;
<Route path={ROUTES.DASHBOARD2} component={Dashboard2} />
Attempted import error: 'FirebaseContext' is not exported from '../Firebase/ContextHookProvider'.
TypeError: Cannot read property 'doCreateUserWithEmailAndPassword' of null
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
setUser(user);
} else {
setUser(false);
}
});
const firebase = useContext(FirebaseContext)
React Hook useEffect has a missing dependency: 'firebase'. Either include it or remove the dependency array
React Hook "useContext" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const devConfig = {
apiKey: process.env.REACT_APP_DEV_API_KEY,
authDomain: process.env.REACT_APP_DEV_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DEV_DATABASE_URL,
projectId: process.env.REACT_APP_DEV_PROJECT_ID,
storageBucket: process.env.REACT_APP_DEV_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_DEV_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_DEV_APP_ID
};
const prodConfig = {
apiKey: process.env.REACT_APP_PROD_API_KEY,
authDomain: process.env.REACT_APP_PROD_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_PROD_DATABASE_URL,
projectId: process.env.REACT_APP_PROD_PROJECT_ID,
storageBucket: process.env.REACT_APP_PROD_STORAGE_BUCKET,
messagingSenderId:
process.env.REACT_APP_PROD_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_PROD_APP_ID
};
const config =
process.env.NODE_ENV === 'production' ? prodConfig : devConfig;
class Firebase {
constructor() {
firebase.initializeApp(config);
this.firebase = firebase;
this.firestore = firebase.firestore();
this.auth = firebase.auth();
}
};
export default Firebase;
import React, { useState, useEffect, useContext, createContext } from "react";
import Firebase from "../firebase";
const authContext = createContext();
// Provider component that wraps app and makes auth object ...
// ... available to any child component that calls useAuth().
export function ProvideAuth({ children }) {
const auth = useProvideAuth();
return <authContext.Provider value={auth}>{children}</authContext.Provider>;
}
// Hook for child components to get the auth object ...
// ... and update when it changes.
export const useAuth = () => {
return useContext(authContext);
};
// Provider hook that creates auth object and handles state
function useProvideAuth() {
const [user, setUser] = useState(null);
const signup = (email, password) => {
return Firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(response => {
setUser(response.user);
return response.user;
});
};
const signin = (email, password) => {
return Firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(response => {
setUser(response.user);
return response.user;
});
};
const signout = () => {
return Firebase
.auth()
.signOut()
.then(() => {
setUser(false);
});
};
const sendPasswordResetEmail = email => {
return Firebase
.auth()
.sendPasswordResetEmail(email)
.then(() => {
return true;
});
};
const confirmPasswordReset = (password, code) => {
// Get code from query string object
const resetCode = code || getFromQueryString("oobCode");
return Firebase
.auth()
.confirmPasswordReset(resetCode, password)
.then(() => {
return true;
});
};
// Subscribe to user on mount
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
setUser(user);
} else {
setUser(false);
}
});
// Subscription unsubscribe function
return () => unsubscribe();
}, []);
return {
user,
signup,
signin,
signout,
sendPasswordResetEmail,
confirmPasswordReset
};
}
const getFromQueryString = key => {
return queryString.parse(window.location.search)[key];
};
import React, { createContext } from 'react';
import Firebase from "../../firebase";
const FirebaseContext = createContext(null)
export { FirebaseContext }
export default ({ children }) => {
return (
<FirebaseContext.Provider value={ Firebase }>
{ children }
</FirebaseContext.Provider>
)
}
ReactDom.render(
<FirebaseProvider>
<App />
</FirebaseProvider>,
document.getElementById("root"));
serviceWorker.unregister();
import React from "react";
import IndexPage from "./index";
import { Switch, Route, Router } from "./../util/router.js";
import { ProvideAuth } from "./../util/auth.js";
function App(props) {
return (
<ProvideAuth>
<Router>
<Switch>
<Route exact path="/" component={IndexPage} />
<Route
component={({ location }) => {
return (
<div
style={{
padding: "50px",
width: "100%",
textAlign: "center"
}}
>
The page <code>{location.pathname}</code> could not be found.
</div>
);
}}
/>
</Switch>
</Router>
</ProvideAuth>
);
}
export default App;
TypeError: _firebase__WEBPACK_IMPORTED_MODULE_2__.default.auth is not a function
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
setUser(user);
} else {
setUser(false);
}
});
TypeError: _util_contexts_Firebase__WEBPACK_IMPORTED_MODULE_8___default(...) is not a function
TypeError: Cannot read property 'onAuthStateChanged' of undefined
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: ...
import React, { useContext } from 'react';
import Firebase from "../../firebase";
export const FirebaseContext = React.createContext();
export const useFirebase = useContext(FirebaseContext);
export const FirebaseProvider = props => (
<FirebaseContext.Provider value={new Firebase()}>
{props.children}
</FirebaseContext.Provider>
);
最佳答案
主要编辑:
花了一些时间对此进行更多研究,这是我想出的一个更干净的解决方案,可能有人不赞成我这是解决此问题的好方法。
使用Firebase身份验证挂钩
import { useEffect, useState, useCallback } from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "xxxx.firebaseapp.com",
databaseURL: "https://xxxx.firebaseio.com",
projectId: "xxxx",
storageBucket: "xxxx.appspot.com",
messagingSenderId: "xxxxxxxx",
appId: "1:xxxxxxxxxx:web:xxxxxxxxx"
};
firebase.initializeApp(firebaseConfig)
const useFirebase = () => {
const [authUser, setAuthUser] = useState(firebase.auth().currentUser);
useEffect(() => {
const unsubscribe = firebase.auth()
.onAuthStateChanged((user) => setAuthUser(user))
return () => {
unsubscribe()
};
}, []);
const login = useCallback((email, password) => firebase.auth()
.signInWithEmailAndPassword(email, password), []);
const logout = useCallback(() => firebase.auth().signOut(), [])
return { login, authUser, logout }
}
export { useFirebase }
firebaseConfig
控制台 =>
项目设置 =>
应用程序 =>
配置单选按钮
useEffect(() => {
const unsubscribe = firebase.auth()
.onAuthStateChanged(setAuthUser)
return () => {
unsubscribe()
};
}, []);
const App = () => {
const { login, authUser, logout } = useFirebase();
if (authUser) {
return <div>
<label>User is Authenticated</label>
<button onClick={logout}>Logout</button>
</div>
}
const handleLogin = () => {
login("name@email.com", "password0");
}
return <div>
<label>User is not Authenticated</label>
<button onClick={handleLogin}>Log In</button>
</div>
}
App
的
create-react-app
组件的基本实现
const useFirestore = () => {
const getDocument = (documentPath, onUpdate) => {
firebase.firestore()
.doc(documentPath)
.onSnapshot(onUpdate);
}
const saveDocument = (documentPath, document) => {
firebase.firestore()
.doc(documentPath)
.set(document);
}
const getCollection = (collectionPath, onUpdate) => {
firebase.firestore()
.collection(collectionPath)
.onSnapshot(onUpdate);
}
const saveCollection = (collectionPath, collection) => {
firebase.firestore()
.collection(collectionPath)
.set(collection)
}
return { getDocument, saveDocument, getCollection, saveCollection }
}
const firestore = useFirestore();
const [document, setDocument] = useState();
const handleGet = () => {
firestore.getDocument(
"Test/ItsWFgksrBvsDbx1ttTf",
(result) => setDocument(result.data())
);
}
const handleSave = () => {
firestore.saveDocument(
"Test/ItsWFgksrBvsDbx1ttTf",
{ ...document, newField: "Hi there" }
);
关于javascript - 带有React Hooks的Firebase监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59977856/
当单击复选框(或选择所有复选框)时,我想向 CheckboxSelectionModel 添加一个监听器。 var smSensors = new xg.CheckboxSelectionModel(
我有一个简单的程序,允许 2 个客户端连接到服务器。 连接后,他们可以轮流点击空白卡片图像。 一旦 2 个客户中的任何一个点击空白卡片图片,卡片图片将变为 Ace 俱乐部图片。 更改将显示在客户端的两
我在这里看到了一个代码,该代码以字符串的形式检索鼠标的当前图标,但是此代码使用了TTimer来实现。 因此,我想知道是否存在某些事件(侦听器)来检测鼠标光标图标上的这些更改。 下面是使用TTimer的
我想在我的配置对象上获得一个 onload 事件。 以下工作,除非我创建一个 config.listeners={..} (我认为这就是我需要的?)替换 this.onload({...}); 我什至
通常,在 Java 中,当我有一个向其他对象提供某种通知的对象时,我将使用 Listener/Observer 模式。 有没有更类似于 Scala 的方式来做到这一点?我应该在 Scala 中使用这种
我有一个带有动画器的游戏对象和一些可以触发事件的动画(具有特定的回调函数)。 只要我将脚本添加到与动画器相同的游戏对象(包括接收器),一切都会正常工作: public class AnimatorEv
我有一个带有监听器的 DialogFragment,用于单击按钮以调用 fragment 中的函数。 我收到 lateinit property listener has not been initi
这个问题已经有答案了: Java ActionListener error: incompatible types (4 个回答) 已关闭 5 年前。 我最近刚刚开始学习 Java 代码。我在添加监听
我的代码遇到问题。我想知道是否有一种更简单的方法来使用监听器,而不是不断地这样做: example.addActionListener(new java.awt.event.ActionListene
有没有办法使用 .net 创建控制台应用程序。或通过某个端口监听 SMTP 消息的服务? 我需要创建一个中间层对象来捕获和处理 smtp 消息。也就是说,我希望该监听器发送和接收 smtp 消息,然后
我有一个带有动画器的游戏对象和一些可以触发事件的动画(具有特定的回调函数)。 只要我将脚本添加到与动画器相同的游戏对象(包括接收器),一切都会正常工作: public class AnimatorEv
我有许多向主事件生成服务注册的监听器。然而,我想告诉听众,事件流在某个时刻将会结束。您会通过简单地调用监听器上的方法(例如 finish())来完成此操作,还是有一个单独的事件方法 streamFin
我的代码有什么问题。 我创建了一个 JList,添加了项目并将其推到左侧(BorderLayout.WEST)。每次单击列表项时,我希望在列表右侧显示一个面板。但问题是,当选择列表项并运行监听器时,到
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 8 年前。 Improve th
这可能是一个简单的问题,但我没有看到它。 我有一个界面 public interface RenderableListener{ public void update(T element);
有人可以直接指出我的正确方向吗?当从组合框中选择适当的选项时,我希望小程序中的 Action 监听器显示从 html 文件检索的 jlabel 中的 3 个参数之一。 干杯 最佳答案 对于组合框,您需
我有一个网站,每个页面上都有许多 jQuery 事件处理程序,所有这些都在一个大型 .js 文件中。 这意味着对于任何页面,大多数事件处理程序都是针对不存在且根本不会使用的 HTML。 这会影响我的表
我有一些 jQuery 监听器设置,用于监听 type="text" 字段上的表单输入。但是,当用户从自动完成下拉框中选择一个选项(即他们之前输入的值已被记住以供将来使用)时,下面的监听器不会收集该值
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 9 年前。 Improve this ques
我正在用 unity (c#) 做一个类似国际象棋的游戏,但我在尝试进行向上转换以将信息从一个 child 发送到另一个抽象类时遇到了困难。 基本上,我有一个抽象类,它有一个带有函数的事件/委托(de
我是一名优秀的程序员,十分优秀!