未定义不是对象(评估"userInfo._name")帮助我



我问你这个问题是因为再次发生错误。我们现在通过axios接收数据,并通过useState((存储数据。因此,如果您在屏幕上创建并立即渲染它,您可以看到数据,但如果您转到上一页并返回,则会发生错误。请让我知道如何解决它。我的错误类型错误:未定义不是对象(正在评估"userInfo_name"(

我的代码

import React, { useState, useEffect } from "react";
import { withNavigation } from "react-navigation";
import { Text, View, StyleSheet, SafeAreaView, Image } from "react-native";
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from "react-native-responsive-screen";
import axios from "axios";
const MyPage = ({ navigation, info }) => {
const [userInfo, setUserInfo] = useState();
const getData = async () => {
try {
axios
.get(
"http://everyweardev-env.eba-azpdvh2m.ap-northeast-2.elasticbeanstalk.com/api/v1/user"
)
.then((res) => res)
.then((data) => {
setUserInfo(data.data.data.result);
})
.catch((err) => console.log(err));
} catch (error) {}
};
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
getData();
});
return unsubscribe;
}, [navigation]);
return (
<View>
{/* <Image source={require("../../images/profile.png")} /> */}
<Text>{userInfo._name}</Text>
<Text>{userInfo._mail}</Text>
</View>
);
};
export default withNavigation(MyPage);

问题发生在userInfo对象为null的初始渲染中。

执行下面的操作,只有当userInfo 有值时才能访问属性

<Text>{userInfo?._name}</Text>
<Text>{userInfo?._mail}</Text>

相关内容

最新更新