在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
相关产品推荐
相关产品推荐

