You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在React或React Native中向列表添加元素并按location属性排序补全占位符

优化实现方案

核心优化点

  • 时间复杂度从O(n*m)降至O(n+m):通过Map做位置映射,避免循环查找索引
  • 减少重渲染次数:仅在生成最终数组后更新1次状态,避免循环内多次触发重渲染
  • 逻辑更直观,维护成本更低

完整优化代码

const [list, setList] = useState([])
const blocks = 4

// 读取存储并生成最终列表的逻辑
const fetchAndBuildList = async () => {
  const jsonValue = await AsyncStorage.getItem('@custom_layout');
  if (jsonValue == null) return;
  
  const rawData = JSON.parse(jsonValue);
  // 若原始数据需要按location排序可加上下面这行
  // rawData.sort((a, b) => a.location - b.location)
  // 构建location到对应数据的映射表
  const locationMap = new Map(rawData.map(item => [item.location, item]));
  
  // 直接生成补全后的最终数组
  const finalList = Array.from({ length: blocks }, (_, index) => {
    // 存在对应位置的数据则直接返回,否则返回占位结构
    return locationMap.get(index) ?? {
      action: 'none',
      location: index,
      title: 'first Demo',
      // 可按需求补充其他占位字段,比如icon、UUID、Children等
    }
  });
  
  // 仅更新一次状态
  setList(finalList);
}

内容的提问来源于stack exchange,提问作者Jerry seigle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:36:03