React状态中用回调函数修改数组报错:Cannot read properties of undefined (reading 'map')
问题原因
你的setShapes回调函数没有返回map生成的新数组,导致shapes状态被设置为undefined,后续遍历的时候自然会抛出"Cannot read properties of undefined (reading 'map')"错误。
修复方案
在回调函数里返回map的结果即可:
修改handleClick函数中的setShapes部分:
setShapes(function(prevData) { // 这里需要return map生成的新数组 return prevData.map(prev => { return { ...prev, y: prev.y + 50 } }) });
或者用箭头函数简化写法,箭头函数单表达式场景可省略大括号和return:
setShapes(prevData => prevData.map(prev => ({ ...prev, y: prev.y + 50 })) );
完整正确代码
let initialShapes = [ { id: 0, type: 'circle', x: 50, y: 100 }, { id: 1, type: 'square', x: 150, y: 100 }, { id: 2, type: 'circle', x: 250, y: 100 }, ]; export default function App() { const [shapes, setShapes] = useState(initialShapes); function handleClick() { setShapes(prevData => prevData.map(prev => ({ ...prev, y: prev.y + 50 })) ); } // 示例渲染逻辑 return ( <div> <button onClick={handleClick}>移动图形</button> {shapes.map(shape => ( <div key={shape.id} style={{ position: 'absolute', left: shape.x, top: shape.y, width: 50, height: 50, borderRadius: shape.type === 'circle' ? '50%' : 0, backgroundColor: 'blue' }}></div> ))} </div> ); }
简单来说:map方法会生成新数组,但你的回调函数没把这个数组返回给setShapes,导致状态被设为undefined。只要在回调里返回map的结果,就能正确更新状态,后续遍历就不会报错了。
内容的提问来源于stack exchange,提问作者chose
相关产品推荐
相关产品推荐

