useContext returns 未定义(React Native、Expo)

useContext returns undefined (React Native, Expo)

我正在尝试检索用户数据(姓名、电子邮件)以在我登录后显示,但我一直收到 undefined 但每当我 console.log( user ) 我看到所有数据,包括姓名和电子邮件

Context.js

import React  from 'react';
const AuthContext = React.createContext();
export default AuthContext;

App.js

import AuthContext from './context';

const App = () => {
  const [user, setUser] = useState();

  return (
    <AuthContext.Provider value={{user, setUser}}>
      <NavigationContainer>
          { user ? <AppNavigator /> : <AuthNavigator/> }
      </NavigationContainer>
    </AuthContext.Provider>
  )
} 

Panel.js

const Panel = ({navigation}) => {
  const { user } = useContext(AuthContext);


  return (
    <View style={styles.container}>
      <Text>Name {user.name} </Text>
      <Text>Email {user.email} </Text>
    </View>
  )
}

Login.js

const handleSubmit = async ( { email, password } ) =>{
    const response = await axios.post(userLogin, 
    { 
        email, 
        password,
    })
    .then((response) => { 
        const user = response.data;
        authContext.setUser(user);
        // console.log(response.data);
    })
    .catch(error => { 
        console.log(error);
    }); 
}

console.log(用户)结果

Object {
  "token": "27|YUHmPPwmRkgQRFkAmbEpSjweXN6QI8eR7O1bHhfd",
  "user": Object {
    "id": 2,
    "name": "maria",
    "email": "maria@mail.com",
    "user_type": "vendor",
    "vendor_address": "55 bola way road",
    "vendor_fullname": "maria smith",
  },
}

感谢您的帮助

可能是因为一开始渲染用户是未定义的,所以你不能访问电子邮件和名称你可以使用 user?.user.?name 这样的电子邮件。 为了验证我所说的,请尝试在 App.js 中提供一个静态用户,您会看到错误消失了