React Router通过对象循环生成路由时无嵌套子路由页面无法访问如何解决
问题原因
你的代码存在以下两个核心问题导致Billing、Regulation路由无法正常渲染:
- 路由配置数组语法错误:Billing配置项末尾有连续两个逗号
,,,会在数组中插入一个undefined空元素,遍历到该元素时访问属性失败,中断后续路由的生成,而Billing、Regulation配置正好在错误逗号之后,因此没有被正确注册到路由表中。 - 列表渲染未加key属性:循环生成的Route组件没有添加唯一key,不符合React列表渲染规范,可能会导致部分元素渲染异常。
修复方案
- 删掉Billing配置项末尾多余的逗号
- 给map遍历生成的Route组件添加唯一key属性,推荐用路由ID作为key值
- 可删除循环外重复的Profile路由声明,避免重复注册
修复后代码
export function RouteStudent(props) { const routeList = [ { "ID": "1", "Name": "Profile", "Description": "", "PathURI": "/profile", "Slug": "Profile", "URI": "/", "Child": [] }, { "ID": "2", "Name": "Product", "Description": "", "PathURI": "/product", "Slug": "Product", "URI": "/", "Child": [ { "ID": "3", "Name": "Item A", "Description": "", "PathURI": "/product/item-a", "Slug": "ItemA", "URI": "/item-a" }, { "ID": "4", "Name": "Item B", "Description": "", "PathURI": "/product/item-b", "Slug": "ItemB", "URI": "/item-b" } ] }, { "ID": "5", "Name": "Sales", "Description": "", "PathURI": "/sales", "Slug": "Sales", "URI": "/", "Child": [ { "ID": "6", "Name": "Sale A", "Description": "", "PathURI": "/sales/sale-a", "Slug": "SaleA", "URI": "/saleA" }, { "ID": "7", "Name": "Sale B", "Description": "", "PathURI": "/sales/sale-b", "Slug": "SaleB", "URI": "/sale-b" } ] }, { "ID": "8", "Name": "Billing", "Description": "", "PathURI": "/billing", "Slug": "Billing", "URI": "/", "Child": [] }, { "ID": "9", "Name": "Regulation", "Description": "", "PathURI": "/regulation", "Slug": "Regulation", "URI": "/", "Child": [] } ]; const COMPONENT_MAP = { 'Dashboard': Dashboard, 'Profile':Profile, 'Product':Product, 'ItemA':ItemA, 'ItemB':ItemB, 'Sales':Sales, 'SaleA':SaleA, 'SaleB':SaleB, 'Billing':Billing, 'Regulation':Regulation, } return ( <Suspense fallback={<h3>Loading..</h3>}> <Switch> <Redirect exact from="/" to="/dashboard"/> <Route path="/dashboard" component={Dashboard} exact/> {routeList.length > 0 ?( routeList.map((v)=> (Object.keys(v.Child).length > 0) ? ( <Route key={v.ID} path={v.PathURI} render={({ match: { url } }) => ( <> <Route path={`${url}/`} component={COMPONENT_MAP[v.Slug]} exact /> {v.Child.map((k)=> <Route key={k.ID} path={`${url+k.URI}`} component={COMPONENT_MAP[k.Slug]} /> )} </> )} /> ) : ( <Route key={v.ID} path={v.PathURI} component={COMPONENT_MAP[v.Slug]} /> ) )) : null } <Route component={PageNotFound}/> </Switch> </Suspense> ) } export default RouteStudent;
内容的提问来源于stack exchange,提问作者Febry Fairuz
相关产品推荐
相关产品推荐

