代码:const JoinContent = props => {const {data} = props;console.log(data);return ( <h1>{data.Category}</h1> );};在控制台日志上我得到{ Category: "a", Logo: "/static/media/army.a5445eab.svg", Eligibility: "a", Exams: "abc" }我在数据中有类别,但在 { data.Category } 上它抛出错误Cannot read Property Category of Undefined我正在研究 React 并使用 Hooks、Context。
1 回答

慕森卡
TA贡献1806条经验 获得超8个赞
如果数据是异步加载的并且它在第一次渲染时不存在,则可能会导致问题。
你有多种方法来解决它
data
如果道具中不存在,则初始化为空对象
const {data = {}} = props; return (<h1>{data.Category}</h1>);
渲染前检查是否
data.Category
存在
return data?.Category && <h1>{data.Category}</h1>;
我更喜欢第二种方法,因为即使data.Category
第一种方法中不存在,也会呈现空的 h1 标签
添加回答
举报
0/150
提交
取消