reactjs - why the component doesn't load in nested routing (react)
问题描述
Here i want to load the ShowIt component as a nested route but it doesn't work i mean when i click on the link i go to route of that but the ShowIt component (hello world) doesn't load and i really need to solve this problem
please help me
import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom';
const ShowIt = <div>Hello world</div>;
const Links = (
<div>
<Link to="news/components">Go to Components</Link>
<br/>
<Link to="news/states-vs-props">Go to states vs props</Link>
</div>
);
const News = () => {
return (
<div>
{
Links
}
<Router>
<Switch>
<Route path="news/:id">
<ShowIt />
</Route>
</Switch>
</Router>
</div>
);
};
export default News;
解决方案
You should not use <Link>
outside a <Router>
. So do this:
<Router>
{Links}
<Switch>
<Route path="/news/:id">
<ShowIt />
</Route>
</Switch>
</Router>
There are few more issues in your code:
- Make
ShowIt
a react component:
const ShowIt = () => <div>Hello world</div>;
- Use a
/some-route
instead ofsome-route
:
<Link to="/news/components">Go to Components</Link>
And, to access id
in ShowIt
component:
import { useParams } from "react-router-dom";
// ...
const { id } = useParams<{ id: string }>();
推荐阅读
- c++ - Unordered_map 或 hashMap 现有散列函数修改?
- anylogic - 功能决定在哪里存放托盘
- vb.net - 在文本文件中查找数字序列
- date - 我正在使用 Sun OS,我希望我的脚本从文件中读取日期(格式为 %Y%m%d)并在该日期上添加 1 天
- python - 如何为“AttributeError:模块'matplotlib.cbook'没有属性'is_string_like'”创建属性?
- lotus-notes - 无法从 Lotus 中标记为“将多个值显示为单独的条目”的列中检索对话列表中的多个值
- python-3.x - '[Errno 26] 文本文件忙:'/home/*****/.wdm/drivers/chromedriver/83.0.4103.39/linux64/chromedriver''
- c# - 参考 DLL 未被替换
- css - 无法在 Gridview 中居中对齐寻呼机编号
- css - 我希望有一个子项要求所有其他元素的宽度