我在<url>/machines
上有一个页面,其中列出了网络上一组机器的IP地址。我想能够在列表中点击一个,并链接到一个页面<url>/machines/<machineid>
渲染一个新的页面,其中显示有关该特定机器的信息。我想在URL中指定的值作为<machineid>
被传递到渲染页面作为一个可用的值,例如在一个道具/参数等
我在配置react路由器来实现这一点时遇到了麻烦,我想知道是否有人能看到我做错了什么?我一直在关注React Router V6文档,但是似乎不能让它工作。当我在<url>/machines/hello
处呈现页面时,我得到一个控制台错误,说No routes matched location "/machines/hello"
。有人能看出我哪里做错了吗?
我最初认为我只是渲染一个新页面(使用不同的组件)来渲染机器信息页面,但是看看React Router V6文档,似乎<MachineInfo>
组件现在被渲染为<Machines>
的子组件?
我在<MachineInfo>
组件中有一个alert()
,似乎根本没有运行。我没有收到警告。
App.js
function App() {
const value = useContext(Context);
return (
<div className="App">
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="machines" element={<Machines />}>
<Route path="machines/:id" element={<MachineInfo />} /> // I've tried this using just path=":id" as well with no luck
</Route>
<Route path="topology" element={<Topology />} />
<Route path="settings" element={<Settings />} />
</Routes>
</div>
);
}
MachineInfo.js
export default function MachineInfo(props) {
const [state, dispatch] = useContext(Context);
let { id } = useParams<"id">([]);
alert("info: " + id)
return (
<p>hello</p>
);
}
首先,您需要一个Layout
组件,它将具有您的Outlet
export function Layout() {
return (
<>
<Outlet />
</>
);
现在将您的其他路由封装在此Layout
组件&你会注意到你现在可以通过输入/machines/1
来进入你的嵌套路由Dashboard
组件是索引,因此/
应该匹配此路由。
function App() {
// Not sure why you have value since it doesn't seem to be getting used
const value = useContext(Context);
return (
<div className="App">
<Routes>
<Route path="/*" element={<Layout />}>
<Route index element={<Dashboard />} />
<Route path="machines" element={<Machines />}>
<Route path=":id" element={<MachineInfo />} />
</Route>
<Route path="topology" element={<Topology />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
</div>
);
}