React使用useState报错:无法读取undefined的'name'属性
问题分析与解决
核心问题
- useState Hook 使用错误:你用了对象解构
const { index, setIndex } = useState(0);,但React的useState返回的是数组而非对象,这种写法会导致index初始值为undefined,直接引发后续访问sculpture.name的错误。 - 索引越界未处理:即使修复了解构问题,当点击Next按钮让
index超过数组最大索引(你的sculptureList只有2个元素,索引范围是0-1)时,sculptureList[index]会返回undefined,同样触发Cannot read properties of undefined错误。
解决步骤
1. 修复useState解构方式
将对象解构改为数组解构,这是React useState的标准用法:
// 错误写法 // const { index, setIndex } = useState(0); // 正确写法 const [index, setIndex] = useState(0);
2. 处理索引边界
有两种常见的处理方式,根据需求选择:
方式一:循环切换(点击到最后一个后回到第一个)
修改handleClick函数,使用取余运算实现循环:
function handleClick(){ setIndex(prevIndex => (prevIndex + 1) % sculptureList.length); }
方式二:到达最后一个后停止切换
当index已经是最后一个元素的索引时,不再增加:
function handleClick(){ setIndex(prevIndex => { return prevIndex < sculptureList.length - 1 ? prevIndex + 1 : prevIndex; }); }
3. 可选:添加渲染守卫(增强健壮性)
可以在渲染时先判断sculpture是否存在,避免意外错误:
let sculpture = sculptureList[index]; if (!sculpture) { return <p>没有更多作品了</p>; }
修改后的完整Gallery.js代码
import { sculptureList } from "./data"; import { useState } from "react"; const Gallery = () => { // 修复useState解构 const [index, setIndex] = useState(0); // 处理边界的点击事件(这里用循环切换为例) function handleClick(){ setIndex(prevIndex => (prevIndex + 1) % sculptureList.length); } let sculpture = sculptureList[index]; return ( <> <button onClick={handleClick}> Next </button> <h2> <i>{sculpture.name}</i> by {sculpture.artist} </h2> <h3>{index + 1} of {sculptureList.length}</h3> <img src={sculpture.url} alt={sculpture.alt} /> <p>{sculpture.description}</p> </> ); } export default Gallery;
内容的提问来源于stack exchange,提问作者InquisitiveLad
相关产品推荐
相关产品推荐

