【发布时间】:2020-10-09 07:14:32
【问题描述】:
我已经使用redux加载了动态分类数据,数据如下:
const categories = [
{ id: 1, name: 'Luxury Boats', url: 'luxury-boat-hire' },
{ id: 2, name: 'Super Yacht Hire', url: 'super-yacht-hire' },
{ id: 3, name: 'Whitsundays', url: 'luxury-boat-hire-whitsundays' },
{ id: 4, name: 'New Years Eve Cruises', url: 'new-years-eve-cruises' }
];
我创建了一个名为 Category.js 的组件。我必须编写路由器代码来覆盖 URL。根据路由器
<Router path=”/category/:id” exact component={Category} />
当我使用 NavLink 并编写代码来设计 NavBar 时,我使用了以下代码。
{
Categories.map(category => {
return <NavLink to={`/category/${category.id}`}>{category.name}</NavLink>
});
}
上面的代码为 4 个类别创建了 4 个 url,例如
Id:1 => http://localhost:3000/category/1
Id:2 => http://localhost:3000/category/2
Id:3 => http://localhost:3000/category/3
Id:4 => http://localhost:3000/category/4
但我想创建一个如下所示的 URL,并且还想在 Category.js 组件中获取 id 参数
Id:1 => http://localhost:3000/category/1 => http://localhost:3000/luxury-boat-hire
Id:2 => http://localhost:3000/category/2 => http://localhost:3000/super-yacht-hire
Id:3 => http://localhost:3000/category/3 => http://localhost:3000/luxury-boat-hire-whitsundays
Id:4 => http://localhost:3000/category/4 => http://localhost:3000/ new-years-eve-cruises
如果我将传递 category.url 而不是 category.id 那么我如何在 Category.js 组件中获取 Id 属性来获取类别详细信息以及与该类别关联的所有产品?我想在 SEO 友好的类别组件和 URL 中获取 id 参数。
对于具有固定 URL 的页面,可以传递 props={category.id}。每个页面的 URL 都是变化的,类别数据是从 mysql 数据库中的 json 数据加载的。我阅读了您的帖子,并且您只有固定的 URL /aboutus。但在我的情况下,所有 URL 和类别名称以及 ID 都是从数据库加载的。
当我使用以下代码将 id 传递给 Category 组件时,URL 第一次工作但当我们刷新页面时 categoryid 变为空:
to={{
pathname: props.link,
categoryid: props.id
}}
请帮忙写一段代码
【问题讨论】:
-
只使用
category.url而不是category.id? -
你可以使用
path="/:cat"和categories.find(cat => this.props.params.match.cat == cat.url) -
作为旁注;你没有提到你是否使用服务器端渲染。如果没有,您的 SEO 友好 URL 将无关紧要。他们仍然对 SEO 不友好。
标签: javascript reactjs router