【问题标题】:Can we create a link with dynamic ID in SPA model我们可以在 SPA 模型中创建具有动态 ID 的链接吗
【发布时间】:2019-06-15 23:19:12
【问题描述】:

我正在使用 ReactJS 开发单页应用程序。我的整个应用程序在单页中运行。现在,我需要一个从 URL 接受使用的 ID 并根据用户 ID 显示结果的页面。 这在 SPA 模型中是否可行,或者我必须将我的网站移动到 MPA 模型?

我尝试了一些答案,但不清楚

例如:https://stackoverflow.com/questions/id/101

我必须获取 ID 101 并根据页面中的 id 显示结果。

【问题讨论】:

标签: 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。

【讨论】:

    【解决方案2】:

    ReactJs 不包含路由器。但是最流行的包是 React-router。 官方文档参考other good packages

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2023-04-08
    相关资源
    最近更新 更多