英文:
How to use multiple paths on the same page?
问题
我有一个组件,我想要创建一个对象或编辑一个对象,基本上我有相同的路径,只是取决于是否有一个id,但是最近react-router-dom不允许我将字符串数组作为参数传递。我该如何实现相同的结果?
return (
<>
<NavBar />
<Container style={{marginTop: '7em'}}>
<Routes>
<Route path='/' Component={HomePage}/>
<Route path='/arenas' Component={ArenaDashboard}/>
<Route path='/arenas/:id' Component={ArenaDetails}/>
<Route path={['/createArena', '/manage/:id']} Component={ArenaForm} />
</Routes>
</Container>
</>
);
英文:
I have a component in which I want to create an object or to edit an object, basically I have the same path, it only depends if it got an id or not, but lately the react-router-dom doesn't allow me to give an array of strings as a parameter. How can I achieve the same result?
return (
<>
<NavBar />
<Container style={{marginTop: '7em'}}>
<Routes>
<Route path='/' Component={HomePage}/>
<Route path='/arenas' Component={ArenaDashboard}/>
<Route path='/arenas/:id' Component={ArenaDetails}/>
<Route path={['/createArena', '/manage/:id']} Component={ArenaForm} />
</Routes>
</Container>
</>
);
答案1
得分: 1
我找到了如何做到这一点:
const location = useLocation();
return (
<>
<NavBar />
<Container style={{marginTop: '7em'}}>
<Routes>
<Route path='/' Component={HomePage}/>
<Route path='/arenas' Component={ArenaDashboard}/>
<Route path='/arenas/:id' Component={ArenaDetails}/>
{['/createArena', '/manage/:id'].map((path) => (
<Route key={location.key} path={path} element={<ArenaForm />} />
))}
</Routes>
</Container>
</>
);
}
请注意,这是一段JavaScript代码,用于在React应用程序中定义路由。
英文:
I found how to do it:
const location = useLocation();
return (
<>
<NavBar />
<Container style={{marginTop: '7em'}}>
<Routes>
<Route path='/' Component={HomePage}/>
<Route path='/arenas' Component={ArenaDashboard}/>
<Route path='/arenas/:id' Component={ArenaDetails}/>
{['/createArena', '/manage/:id'].map((path) => (
<Route key={location.key} path={path} element={<ArenaForm />} />
))}
</Routes>
</Container>
</>
);
}```
</details>
# 答案2
**得分**: 0
你可以明确将其定义为:
```jsx
return (
<>
<NavBar />
<Container style={{marginTop: '7em'}}>
<Routes>
<Route path='/' Component={HomePage}/>
<Route path='/arenas' Component={ArenaDashboard}/>
<Route path='/arenas/:id' Component={ArenaDetails}/>
<Route path='/createArena' Component={ArenaForm} />
<Route path='/manage/:id' Component={ArenaForm} />
</Routes>
</Container>
</>
);
英文:
You may explicitly define it as:
return (
<>
<NavBar />
<Container style={{marginTop: '7em'}}>
<Routes>
<Route path='/' Component={HomePage}/>
<Route path='/arenas' Component={ArenaDashboard}/>
<Route path='/arenas/:id' Component={ArenaDetails}/>
<Route path='/createArena' Component={ArenaForm} />
<Route path='/manage/:id' Component={ArenaForm} />
</Routes>
</Container>
</>
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论