我们可以在 SPA 模型中创建一个带有动态 ID 的 link
Can we create a link with dynamic ID in SPA model
我正在使用 ReactJS 开发单页应用程序。我的整个应用程序在单页中是 运行。现在,我需要一个页面来接受来自 URL 的已用 ID 并根据用户 ID 显示结果。
这在 SPA 模型中是否可行,或者我必须将我的网站移动到 MPA 模型?
我尝试了一些答案,但不是很清楚
例如:https://whosebug.com/questions/id/101
我必须获取ID 101,并根据该ID在页面中显示结果。
ReactJs 不包含路由器。但最流行的软件包是 React-router。
官方文档参考other good packages
是的,确定这是可能的。
让我给你一些背景知识。如果您正在构建具有多个页面的 SPA,您希望在 otder 中使用客户端路由来显示基于浏览器的不同页面 url。据我所知,反应中路由的实际解决方案是 react-router but there are many other to chose from. 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
文档。
我正在使用 ReactJS 开发单页应用程序。我的整个应用程序在单页中是 运行。现在,我需要一个页面来接受来自 URL 的已用 ID 并根据用户 ID 显示结果。 这在 SPA 模型中是否可行,或者我必须将我的网站移动到 MPA 模型?
我尝试了一些答案,但不是很清楚
例如:https://whosebug.com/questions/id/101
我必须获取ID 101,并根据该ID在页面中显示结果。
ReactJs 不包含路由器。但最流行的软件包是 React-router。 官方文档参考other good packages
是的,确定这是可能的。
让我给你一些背景知识。如果您正在构建具有多个页面的 SPA,您希望在 otder 中使用客户端路由来显示基于浏览器的不同页面 url。据我所知,反应中路由的实际解决方案是 react-router but there are many other to chose from. 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
文档。