1 回答

TA貢獻1775條經驗 獲得超8個贊
我 99% 確定您的問題是因為您使用了超過 1 個路由器。刪除UIBrowserRouter周圍的內容Settings。我猜測當嵌套路由沒有通過外部路由器的鏈接導航到時,該match道具不會像您期望的那樣初始化。
const Settings = (props) => {
let { path, url } = useRouteMatch();
return (
<div className="Settings">
<nav>Navigation bar</nav>
<div className="SettingsWrapper">
<Switch>
<Route path={`${path}/editprofile`} component={EditProfile} />
<Route
path={`${path}/changepassword`}
component={ChangePassword}
/>
<Route path={`${path}/changepin`} component={ChangePin} />
<Route
path={`${path}/accountsettings`}
component={BankSettings}
/>
</Switch>
</div>
</div>
);
};
編輯
好吧,當刪除嵌套路由器并創建我自己的代碼和盒子時,我發現了嵌套路由的一個小、微妙但重要的“怪癖”。任何渲染更多路由的嵌套路由都不能指定exact路由上的 prop。
const App = () => {
let { path, url } = useRouteMatch();
return (
<div className="App">
<nav>Navigation bar</nav>
{/* setting up the routes */}
<div className="MainBody">
<Switch>
...
<Route
path={`${path}/settings`}
exact // <-- exact match precludes sub-routes!!
component={Settings}
/>
</Switch>
</div>
</div>
);
};
因此,如果路徑是“/dashboard/settings/editprofile”,則路徑不再與路由路徑完全匹配,并且不會呈現路由。
解決方案
exact只需省略嵌套路由渲染子路由的 prop即可。請記住,路由路徑將被視為“前綴”,因此如果沒有exact指定 prop,路徑“/dashboard/settings/editprofile”可以與“/dashboard/settings”匹配。
const Dashboard = () => {
let { path, url } = useRouteMatch();
return (
<div className="App">
<nav>Dashboard Navigation bar </nav>
<NavLink to={`${url}/settings`}>Settings</NavLink>
{/* setting up the routes */}
<div className="MainBody">
<Switch>
...
<Route path={`${path}/settings`} component={Settings} /> // <-- no exact match
</Switch>
</div>
</div>
);
};
添加回答
舉報