【问题标题】:Can we create a link with dynamic ID in SPA model我们可以在 SPA 模型中创建具有动态 ID 的链接吗
【发布时间】:2019-06-15 23:19:12
【问题描述】:
【问题讨论】:
标签:
reactjs
dynamic
single-page-application
multi-page-application
【解决方案1】:
是的,这是可能的。
让我给你一些背景知识。如果您正在构建具有多个页面的 SPA,您希望在 otder 中使用客户端路由来根据浏览器 url 显示不同的页面。据我所知,react 中路由的实际解决方案是react-router,但还有许多其他选择。 See this link。不幸的是,我无法完全解释如何使用react-router 解决方案,但这里是一个简短的示例。
在您的主要组件(如 App.jsx)中添加路由:
// 1. do proper imports
import { BrowserRouter } from "react-router-dom";
// 2. wrap your application inside of BrowserRouter component
class App extends React.Component {
// your code
render() {
return (
<BrowserRouter>
{/* your app code */}
{/* Add routing */}
<Route path="/" exact component={Dashboard} />
<Route path="/questions/id/:id" component={Question} />
{/* your app code */}
<BrowserRouter>
)
}
}
您现在应该看到,当您的浏览器 url 匹配 /questions/id/:id 组件时,Question 应该被挂载到页面上。在这个组件中,您可以获取传入的id。它将在this.props.match.param.id 属性中
class Question extends React.Component {
// your code
render() {
const id = this.props.match.param.id;
return (
<div>
Page with { id } was opened
<div>
)
}
}
确定您想熟悉react-router docs。