1

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

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

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

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

4

2 回答 2

3

是的,这是可能的。

让我给你一些背景知识。如果您正在构建具有多个页面的 SPA,您希望在 otder 中使用客户端路由来根据浏览器 url 显示不同的页面。据我所知,react 中路由的实际解决方案是react-router但还有许多其他可供选择。请参阅此链接。不幸的是,我无法完全解释如何使用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文档。

于 2019-01-22T15:15:03.480 回答
0

ReactJs 不包含路由器。但是最流行的包是 React-router。官方文档参考了其他不错的包

于 2019-01-22T13:31:48.487 回答