我有一个标题导航栏,其中包含以下各项:主页,类别,关于我们和联系方式。类别里面是一个子导航栏,其中包含3个项目:书籍,食物和电影。问题是反应路由器,每次我从子导航栏中选择项目时,它总是转到类别组件。其他标题项目工作正常。这是我的代码:
pageRouters.js:
import Home from '../components/home';
import Category from '../components/category';
import AboutUS from '../components/about';
import Contact from '../components/contact';
import Book from '../components/category/book';
import Food from '../components/category/food';
import Movie from '../components/category/movie';
export const cat_url = 'category';
export const about_url = 'about';
export const contact_url = 'contact';
export const book_url = 'books';
export const food_url = 'food';
export const movie_url = 'movie';
const pageRouters = [
{
name: 'Home',
path: '/',
component: Home,
exact: true
},
{
name: 'Categories',
path: `/${cat_url}`,
component: Category,
items: [
{
name: 'Books',
path: `/${cat_url}/${book_url}`,
component: Book,
},
{
name: 'Food',
path: `/${cat_url}/${food_url}`,
component: Food,
},
{
name: 'Movie',
path: `/${cat_url}/${movie_url}`,
component: Movie,
}
]
},
{
name: 'About',
path: `/${about_url}`,
component: AboutUS
},
{
name: 'Contact',
path: `/${contact_url}`,
component: Contact
}
];
export default pageRouters;
Header.js:
import React, { PureComponent } from 'react';
import { Route, Link } from 'react-router-dom';
import pageRouters from '../pageRouters';
class Header extends PureComponent {
constructor(props) {
super(props);
this.state = {
routers: pageRouters
};
}
render() {
const { routers } = this.state;
return (
<div id="header">
{routers.length && (
<ul className="nav">
{routers.map((url, key) => {
if (url.name === 'Categories') {
return (
<li key={key}>
{url.name}
<ul id='subNav'>
{url.items.map((item, key) => {
return (
<Route key={key} path={item.path} exact={item.exact}>
<li>
<Link to={item.path}>
{item.name}
</Link>
</li>
</Route>
);
})}
</ul>
</li>
);
}
return (
<Route key={key} path={url.path} exact={url.exact}>
<li>
<Link to={url.path}>
{url.name}
</Link>
</li>
</Route>
);
})}
</ul>
)}
</div>
);
}
}
export default Header;
答案 0 :(得分:0)
我认为您必须像这样声明路线参数
const pageRouters = [
{
name: 'Home',
path: '/',
component: Home,
exact: true
},
{
name: 'Categories',
path: `/${cat_url}`,
component: Category,
items: [
{
name: 'Books',
path:/category/:bookId,
component: Book,
},
{
name: 'Food',
path:/category/:FoodId,
component: Food,
},
{
name: 'Movie',
path:/category/:MovieId,
component: Movie,
}
]
},
{
name: 'About',
path: `/${about_url}`,
component: AboutUS
},
{
name: 'Contact',
path: `/${contact_url}`,
component: Contact
}
];