我正在尝试在 React Native Expo 应用程序中使用 Firebase 实现身份验证,但收到指向 useContext
的错误,我在我的 Routes.js 文件中使用了该错误:
import React, { useContext, useEffect, useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import * as firebase from 'firebase';
import AuthStack from './AuthStack';
import MainTab from './MainTab';
import { AuthUserContext } from './AuthUserProvider';
import LoadingScreen from '../screens/LoadingScreen';
export default function Routes() {
const [isLoading, setIsLoading] = useState(true);
const { user, setUser } = useContext(AuthUserContext);
useEffect(() => {
const unsubscribeAuth = firebase.auth().onAuthStateChanged(async authUser => {
try {
await (authUser ? setUser(authUser) : setUser(null));
setIsLoading(false);
} catch (error) {
console.log(error);
}
});
return unsubscribeAuth;
}, []);
if (isLoading) {
return <LoadingScreen />;
}
return (
<NavigationContainer>
{user ? <MainTab /> : <AuthStack />}
</NavigationContainer>
);
}
我在单独的文件 AuthUserContext
中创建 AuthUserProvider.js
:
import React, { useState, createContext } from 'react';
export const AuthUserContext = createContext({});
export const AuthUserProvider = ({ children }) => {
const [user, setUser] = useState(null);
return (
<AuthUserContext.Provider value={{ user, setUser }}>
{children}
</AuthUserContext.Provider>
);
};
然后我将其用作 App.js 文件中的提供程序:
export default function AppWrapper() {
const [fontLoaded, setFontLoaded] = useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => setFontLoaded(true)}
/>
);
}
const rootReducer = combineReducers({
cart: cartReducer,
history: historyReducer
});
const store = createStore(rootReducer, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<AuthUserProvider>
<Routes />
</AuthUserProvider>
</Provider>
);
}
我几天来一直在寻找答案,但看不出这有什么问题。我使用 createContext
或 useContext
的方式有问题吗?任何有关可能解决方案的线索都会让我永远感激不尽!!