我正在将我的React应用程序迁移到firebase v9。目前,我正在研究auth上下文。
问题是onAuthStateChanged()
回调只在初始化期间触发一次,而不是signInWithEmailAndPassword()
或signOut()
。刷新页面显示验证状态确实发生了变化,只是侦听器不会触发。
v9中是否有任何变化可能导致此问题,或者我错过了什么?
上下文
AuthContext.jsx
export const AuthContext = createContext(undefined);
export const AuthWrapper = ({ children }) => {
const [user, setUser] = useState(undefined);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return unsubscribe();
}, []);
return <AuthContext.Provider value={user}>{children}</AuthContext.Provider>;
};
使用
index.jsx
import { AuthWrapper } from "./context/AuthContext";
ReactDOM.render(
<React.StrictMode>
<AuthWrapper>
<App />
</AuthWrapper>
</React.StrictMode>,
document.getElementById("root")
App.jsx
import { useContext } from "react";
import { AuthContext } from "./context/AuthContext";
function App() {
const user = useContext(AuthContext);
return <>{user ? <Dashboard /> : <Landing />}</>
}
我认为你的清理效果设置是错误的。
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
// to fix:
return () => { unsubscribe() }
// equivalent to:
return unsubscribe
// but not:
return unsubscribe(); // it cleans up immediately after the first call
}, []);