TypeError 中的错误:无法读取 undefined 的属性(读取“name”)

Error in TypeError: Cannot read properties of undefined (reading 'name')

提问人:Aniw Anie 提问时间:11/6/2022 更新时间:11/6/2022 访问量:4725

问:

我正在尝试创建一个点击事件,以便能够删除列表中的项目,但是当我单击它时,我收到“TypeError:无法读取未定义的属性(读取'name')”。

我很确定在某个地方绑定“这个”是要做的事情,但我尝试了很多地方,但它不起作用。enter image description here

这是我的代码:

import React from "react";
import { useRecoilValue } from "recoil";

import { userProfile } from "../recoil";
import ProfileName from "./components/profileName";

const DetailProfil = () => {
  const profile = useRecoilValue(userProfile);

  return (
    <div>
      <ProfileName
        profilePicture={profile?.profilePicture}
        fullName={profile?.fullname}
        roleDetails={profile?.details.name}
      />

      
    </div>
  );
};

export default DetailProfil;
javascript reactjs 这个 react-props

评论

2赞 Konrad 11/6/2022
detailsundefined
0赞 Andy 11/6/2022
因为在这一点上可能没有定义,所以它是有道理的,也没有。所以也应该检查一下。profiledetails

答:

3赞 Sachila Ranawaka 11/6/2022 #1

将可选运算符也添加到 details 对象

roleDetails={profile?.details?.name}
1赞 Layeb Mazen 11/6/2022 #2

您可以使用 Optional chainingNullish 合并运算符

roleDetails={profile?.details?.name ?? 'YOUR_DEFAULT_ROLE_HERE'}