大家好,对不起我的英语
让我们假设我有page1在数据库中有内容,和page2在数据库中有不同的内容,但是page1和page2共享相同的模板,我只想根据URL或id改变内容,如果用户请求page2的URL,他将得到page2的内容和其他页面相同的内容
我是MERN Stack的新手,请给我简单的解决方案:)
我不知道怎么做,对不起我的英语
为此,您将需要使用一种称为路由器的东西。react最流行的路由器是社区构建的
要安装它,请运行以下命令:
npm i --save react-router-dom
设置通常在
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
下面是你如何定义你的不同路线:
export default function App() {
return (
<Router>
<Switch>
<Route path="/posts">
<PostsContainer />
</Route>
<Route path="/post/:id"> // the `:id` tells the router that this is a URL argument.
<Post />
</Route>
</Switch>
</Router>
)
}
最后,访问组件中
下面是组件内部的情况:
const Post = props => {
const params = useParams()
return (
<Fragment>
{params.id} // will render the url parameter with the key of id.
</Fragment>
)
}
此外,在此组件中,您可以进行API调用以获取具有特定ID的post,或者在使用某种全局状态管理框架或工具时将其从全局存储中筛选出来。
访问此链接以获取更多的最新信息,以防您将来阅读此链接或需要更多信息。