React Native useContext钩子返回未定义

时间:2020-04-23 05:08:47

标签: react-native context-api

我是本机和上下文Api的新手,所以我们将不胜感激。启动应用程序时,我看到未定义不是对象_useContext.appUser错误。下面是我的代码。 App.js

import { AsyncStorage } from 'react-native';
import { NavigationContainer } from '@react-navigation/native'
import AuthStackNavigator from './src/navigators/AuthStackNavigator'
import { LightTheme } from './src/themes/light'
import UserTabsNavigator from './src/navigators/UserTabsNavigator'
import AuthProvider from './src/auth/AuthProvider'
import { AuthContext } from './src/auth/AuthProvider';




export default function App() {

  const [loggedIn, setLoggedIn] = useState(false);
  const { appUser } = useContext(AuthContext);

  console.log('context object' + appUser);

  useEffect(() => {
    AsyncStorage.getItem('user').then(userString => {
      if (userString) {
        setLoggedIn(true)
      }
    }).catch(error => {
      console.log(error);
    })
  })


  return (
    <AuthProvider>
      <NavigationContainer theme={LightTheme}>
        {loggedIn ? <UserTabsNavigator /> :
          <AuthStackNavigator />}

      </NavigationContainer>
    </AuthProvider>
  );

};

AuthProvider.js

import React, { useState, createContext } from 'react';
import { AsyncStorage } from 'react-native';


export const AuthContext = createContext();

const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(null);

    const loginUser = () => {
        const fakeUser = { username: 'Test' }
        AsyncStorage.setItem('user', JSON.stringify(fakeUser));
        setUser(fakeUser);

    }

    const logoutUser = () => {
        AsyncStorage.removeItem('user');
        setUser(null);
    }


    return (
        <AuthContext.Provider value={{
            appUser: user,
            login: loginUser,
            logout: logoutUser

        }}>
            {children}
        </AuthContext.Provider>
    )
}

export default AuthProvider;

我非常感谢您的帮助。我已经为这个问题苦苦挣扎了一段时间了。我有点卡在这里。

0 个答案:

没有答案