React状态数组中LINK对象uri与前置同类型对象uri拼接问题
问题:React状态数组生成层级化路径失败
需求说明
需要将React状态数组navigation中每个LINK类型对象的uri字段,与之前所有同类型对象的uri拼接,生成层级化路径。
初始状态数组
navigation:[ { "type": "LINK", "uri": "arbress" }, { "type": "LINK", "uri": "arbres-a-grand-developpement" }, { "type": "LINK", "uri": "Acer-xfreemanii" } ]
期望结果
navigation:[ { "type": "LINK", "uri": "arbress" }, { "type": "LINK", "uri": "arbress/arbres-a-grand-developpement" }, { "type": "LINK", "uri": "arbress/arbres-a-grand-developpement/Acer-xfreemanii" } ]
原代码问题分析
你写的这段useEffect没生效,问题出在这几个地方:
- 内层
map里判断obj2 === 'LINK'完全错误,obj2是对象,应该判断obj2.type === 'LINK' - 内层
map的返回值根本没被接收,外层if块里没有返回任何处理后的对象,直接走到了return obj1,所以原数组完全没变化 - 拼接时用的
uri是未定义的变量,逻辑上也不对,应该用累积的路径来拼
正确解决方案
这里提供两种可行写法,都能实现需求:
写法一:map配合累加数组
useEffect(() => { let pathAccumulator = []; const newNavigation = navigation.map(item => { if (item.type === 'LINK') { pathAccumulator.push(item.uri); return { ...item, uri: pathAccumulator.join('/') }; } // 非LINK类型直接返回原对象 return item; }); setNavigation(newNavigation); }, []);
写法二:用reduce累积构建
useEffect(() => { const newNavigation = navigation.reduce((acc, current) => { if (current.type === 'LINK') { // 获取上一个LINK的路径(如果存在) const lastUri = acc.length && acc[acc.length - 1].type === 'LINK' ? acc[acc.length - 1].uri : ''; const newUri = lastUri ? `${lastUri}/${current.uri}` : current.uri; acc.push({...current, uri: newUri}); } else { acc.push(current); } return acc; }, []); setNavigation(newNavigation); }, []);
关键说明
- 两种写法都会保留非
LINK类型的对象原样,只处理目标类型的元素 - 核心逻辑是累积之前所有LINK的uri路径,每次遇到新的LINK就把当前uri拼到后面
- 注意不要直接修改原状态对象,必须返回新对象来保证React状态更新生效
内容的提问来源于stack exchange,提问作者HICHEM NEGGAZ
相关产品推荐
相关产品推荐

