当需要从后端获取特定的值时,面对错误反应



我试图从后端获得值,它显示完全好,并在控制台上抓取所有属性,但当我想访问一个特定的值它显示一个错误,但有时它的工作,我已经尝试使用效果依赖关系,但仍然相同,Uncaught TypeError: Cannot read properties of undefined (reading 'eventName')示例JSON格式:

0: {eventFeeStudent:"34";eventName:"新事件";eventNotificationsDate:"2022 - 05 - 23 t18:00:00.000z"}

这里工作得很好,但当想要捕获任何特定的密钥对,如eventName,我得到错误。

const EventEditNavbar = () => {
const { user } = useAuth();
const [userInfo, setUserInfo] = useState({});
console.log(userInfo);
console.log(user);
// console.log(userInfo[0].eventName);
const eventName = userInfo[0].eventName;


useEffect(() => {
if (!user || !user.email) return
const uri = `http://localhost:5000/findevents/?userEmail=${user.email}`;
fetch(uri)
.then((res) => res.json())
.then((data) => setUserInfo(data));
}, [user]);
return (
<Container>
<div className="eventEdit_nav">
<div className="eventEdit_nav_right">
<Link to={`/festivals/${eventName}`}>View</Link>
<Link to="/">Edit</Link>
<Link to="">Manage</Link>
<Link to="">Marketing</Link>
</div>
<div className="eventEdit_nav_left">
<Link to="">Save</Link>
<Link to="">List Event</Link>
</div>
</div>
</Container>
);
};
export default EventEditNavbar;

请记住,当一个对象的属性是undefined时,访问它的子属性将抛出一个未捕获的错误,这意味着在未定义的属性下面没有任何东西。

在您的示例中,您用一个空对象({})初始化userInfo,因此首先的userInfo[0](当没有从服务器获取数据时)将是undefined,并且当您试图访问它的子对象时,它将抛出错误。为了解决这个问题,你可以使用可选的链接,每当你尝试这样做的时候。

那么这样做将解决您的问题:

const eventName = userInfo[0]?.eventName;
/* Whenever userInfo is undefined the eventName will
be set to undefined as well and it will prevent the
application from throwing an error when you try to
access userInfo child */

相关内容

最新更新