ReactJS:交换对象属性中数组元素时出现TypeError错误求助
问题分析与修复
错误原因
你在更新state时,错误地将container属性赋值为一个函数,而不是数组。React更新后,arr.container变成了函数类型,函数没有map方法,因此触发TypeError: arr.container.map is not a function错误。
修复方案
移除container的函数包裹逻辑,直接计算交换后的数组,并增加边界判断避免索引越界:
import { useState } from 'react' export default function App() { const [arr, setArr] = useState({container: [{num: 0}, {num: 1}]}) return ( <div> {arr.container.map((element, index) => ( <div key={index}> <button onClick={() => setArr(prevArr => { // 第一个元素不执行交换,避免索引越界 if (index === 0) return prevArr; // 复制原数组,避免直接修改state const newContainer = [...prevArr.container]; // 交换当前元素与前一个元素的位置 const temp = newContainer[index]; newContainer[index] = newContainer[index - 1]; newContainer[index - 1] = temp; return { ...prevArr, container: newContainer }; })}>^</button> <p>{ element.num }</p> </div> ))} </div> ); }
关键修改点
- 移除
container属性的函数赋值,直接生成新数组并赋值给container。 - 增加
index === 0的判断,防止点击第一个元素按钮时出现异常交换。 - 给列表元素添加
key属性,符合React列表渲染的规范。
内容的提问来源于stack exchange,提问作者bascott
相关产品推荐
相关产品推荐

