我正在开发一个 React 应用程序,该应用程序使用 React Router 进行路由,并使用 Redux 进行状态管理。我遇到一个问题,导航到 /shop/hats 会导致控制台错误:“没有与位置 '/shop/hats' 匹配的路线
App.js:
import React from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import ShopPage from "./pages/shop/shop.component";
import HomePage from "./pages/homepage/homepage.component";
import CheckoutPage from "./pages/checkout/checkout.component";
import SignInAndSignUpPage from "./pages/sign-in-and-sign-up/sign-in-and-sign-up.component";
const App = () => (
<Router>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/shop/" element={<ShopPage />} />
<Route path="/checkout" element={<CheckoutPage />} />
<Route path="/signin" element={<SignInAndSignUpPage />} />
</Routes>
</Router>
);
export default App;
ShopPage.js:
import React from "react";
import { Routes, Route } from 'react-router-dom';
import CollectionsOverview from '../../components/collections-overview/collections-overview.component';
import CollectionPage from "../collection/collection.component";
const ShopPage = () => (
<div className="shop-page">
<Routes>
<Route path="/" element={<CollectionsOverview />} />
<Route path="/:categoryId" element={<CollectionPage />} />
</Routes>
</div>
);
export default ShopPage;
目录.reducer.js:
const INITIAL_STATE = {
sections: [
{
title: 'hats',
imageUrl: 'https://i.ibb.co/cvpntL1/hats.png',
id: '1',
linkUrl: 'shop/hats'
},
{
title: 'jackets',
imageUrl: 'https://i.ibb.co/px2tCc3/jackets.png',
id: '2',
linkUrl: 'shop/jackets'
},
// ... other sections
]
};
const directoryReducer = (state = INITIAL_STATE, action) => {
switch(action.type) {
default:
return state;
}
};
export default directoryReducer;
shop.reducer.js:
import SHOP_DATA from "./shop.data";
const INITIAL_STATE = {
collections: SHOP_DATA
}
const shopReducer = (state = INITIAL_STATE, action) => {
switch(action.type) {
default:
return state;
}
};
export default shopReducer;
shop.selectors.js:
import { createSelector } from "reselect";
const selectShop = state => state.shop;
export const selectCollections = createSelector(
[selectShop],
shop => shop.collections
);
export const selectCollection = collectionUrlParam => (
createSelector(
[selectCollections],
collections => collections.find(
collection => collection.id === COLLECTION_ID_MAP[collectionUrlParam]
)
)
);
导航至
"/shop/hats"
、"/shop/jackets"
或"/shop/sneakers"
等路线以及其他剩余路线时。我希望应用程序显示 CollectionPage
组件以及每个集合的相应图像和数据。
您需要确保嵌套路径(如
/shop/hats
)未排除在路由定义中。您需要确保 ShopPage.js
正确渲染子路由。
<Route path="/shop/*" element={<ShopPage />} />
*
字符允许路由器匹配商店页面下的所有子路径,包括您定义的路径,帽子和夹克。
您还需要在定义
ShopPage.js
路由时删除 :categoryId
中的正斜杠。
<Route path=":categoryId" element={<CollectionPage />} />
由于该路线直接位于
/shop
下,因此它会自动匹配其下的任何类别。
所以你的路由定义不匹配。