如何在React中使用.splice()截取最近10条操作并修复list不可迭代错误
错误根本原因
你的TypeError: list is not iterable报错核心是初始状态类型错误:
你初始给list的默认值是{}对象,而扩展运算符[...list]只能遍历数组/类数组结构,遍历对象自然会抛出不可迭代的错误。
代码中其他隐含问题
- 初始代码的数组长度判断逻辑错误:你写的
currentListCopy >= 10是拿整个数组和数字对比,永远返回假,应该判断数组的.length属性 - 不要在组件主渲染流程中直接调用
setList,会触发无限重渲染 - 你更新后的版本把
storeList放进useEffect依赖项,但你在effect中同时发起请求修改store、又监听store变化,会导致请求重复触发死循环 useEffect不能直接传入async函数,React会抛出警告,因为effect的返回值应该是清理函数,而async函数返回的是Promise
修复方案
不需要额外维护本地list状态,直接从Redux取数据后截取前10条展示即可,逻辑更简洁:
- 先确保Redux中
operations的初始值设为空数组[] - 用
slice方法截取数组前10项,比splice更合适,因为slice不会修改原数组,是纯函数操作 - 移除冗余的本地状态和重复逻辑
完整修复后代码:
export default function ListOperations() { const dispatch = useDispatch(); // 直接从store取操作列表,保证store中operations初始值为[] const operationList = useSelector((state) => state.operations); React.useEffect(() => { // 把异步逻辑封装在effect内部的函数中,避免async useEffect警告 const fetchOperations = async () => { try { const response = await axios.get("http://localhost:3000/operation"); dispatch({ type: "LIST_OPERATIONS", list: response.data, }); } catch (e) { swal("Error", e.message, "error"); } } fetchOperations(); }, [dispatch]); // 依赖项只放稳定的dispatch,避免重复触发请求 // 直接截取前10条,数组长度不足10时自动返回全部内容,无需额外判断 const showList = operationList.slice(0, 10); return ( <div> <div> <h2>OPERATIONS HISTORY:</h2> </div> <table> <thead> <tr> <th>ID</th> <th>Reason</th> <th>Amount</th> <th>Date</th> <th>Type</th> </tr> </thead> <tbody> {showList.map((oneOperation) => ( <tr key={oneOperation.id}> <td>{oneOperation.id}</td> <td>{oneOperation.reason}</td> <td>{oneOperation.amount}</td> <td>{oneOperation.date}</td> <td>{oneOperation.type}</td> </tr> ))} </tbody> </table> </div> ); }
内容的提问来源于stack exchange,提问作者Ignacio Garcia
相关产品推荐
相关产品推荐

