英文:
Editing a useParams ID to use as a proper title in React
问题
以下是已翻译的内容:
这是我的路由配置:
<Route path="/marvel" element={<Marvel />} />
<Route path="/marvel/:id" element={<MarvelDetail />} />
这是我的 Marvel 页面:
<a href="/marvel/captain-america-civil-war">
Captain America: Civil War
</a>
这是我的 Detail
页面:
const { id } = useParams();
<div className="marvel__main-topbar">
<span className="marvel__main-title">{id}</span>
</div>
我有一个主页面,可以重定向到与特定漫威电影相关的任意数量的主题。如果您查看 Detail
页面的代码,您会注意到我有一个带有 { id }
的 span
用于显示在每个页面的顶部。路由正常工作,我被重定向到正确的页面,但是标题不是 Captain America: Civil War
,而是 captain-america-civil-war
。我知道它这样做是因为它只是复制了路由。但是,我如何使每个页面都有自己的正确标题,而不是使用短横线?
我尝试过的方法:
我将 id
更改为包括 replace
方法,但这并没有完全起作用,因为它不知道何时包含冒号或任何其他特殊字符。
英文:
Here's my Routing
<Route path="/marvel" element={<Marvel />} />
<Route path="/marvel/:id" element={<MarvelDetail />} />
Here's my Marvel page
<a href="/marvel/captain-america-civil-war">
Captain America: Civil War
</a>
Here's my Detail
page
const { id } = useParams();
<div className="marvel__main-topbar">
<span className="marvel__main-title">{id}</span>
</div>
I have a main page that redirects to any number of topics relating to a specific Marvel movie. If you take a look at the Detail
page code you'll notice I have a span
with { id }
for the title which displays at the very top of each page. The routing works fine and I'm redirected to the right page, however instead of having the title be Captain America: Civil War
it makes it captain-america-civil-war
. I know it does this because it's just copying the route. But how can I make each page have their own proper title instead of one that uses dashes?
What I've Tried
I changed the id
to include the replace
method but that didn't fully work because it doesn't know when to include a colon or any other special characters.
答案1
得分: 1
以下是翻译好的内容:
marvelDetails.js
const marvelDetails = [
{
id: 'captain-america-civil-war',
title: '美国队长:内战'
},
];
在您的详情页面:
const { id } = useParams();
// 不要忘记导入 marvelDetails.js 文件
const title = marvelDetails.find((detail) => detail.id === id).title;
<div className="marvel__main-topbar">
<span className="marvel__main-title">{title}</span>
</div>
英文:
What you could do is create a separate file that contains an array of marvel objects with the id AND the proper title like so :
marvelDetails.js
const marvelDetails = [
{
id: 'captain-america-civil-war',
title: 'Captain America: Civil War'
},
];
In your Details page:
const {id} = useParams();
// Don't forget to import the marvelDetails.js file
const title = marvelDetails.find((detail) => detail.id === id).title
<div className="marvel__main-topbar">
<span className="marvel__main-title">{title}</span>
</div>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论