【问题标题】:How to render components in react-router-dom with bundle.js file?如何使用 bundle.js 文件渲染 react-router-dom 中的组件?
【发布时间】:2019-07-11 04:19:48
【问题描述】:

我创建了一个网络应用程序并使用 react-router-dom 在应用程序中进行导航。当我使用 webpack-dev-server 启动应用程序时一切正常,现在是时候在我的服务器上部署这个应用程序了,所以我使用 webpack 命令创建了这个应用程序的包文件,但是 react-router-dom 没有渲染任何组件使用 bundle.js 文件,我添加或不添加开关。

当我单击 URL 或刷新页面时,即使在 webpack-dev-server 中,我也会收到错误“找不到网页”。我希望我的应用程序也可以使用 url,而不仅仅是使用 Link 和 Push。这是我的代码

import {        
    Router,
    Route,
    Switch
} from "react-router-dom";
import { Provider } from "react-redux";
import history from "./config/History";

import store from "./store";

const router = (
    <Provider store={store}>
        <Router history={history}>
            <div>
                <Header />
                <Switch>
                    <Route exact path="/" component={Login} />
                    <Route path="/login" component={Login} />
                    <Route path="/create/questions" component={CreateQuestion} />
                    <Route path="/create/quiz" component={CreateQuiz} />
                </Switch>
            </div>
        </Router>
    </Provider>
)

ReactDOM.render(router, document.getElementById("root"));

【问题讨论】:

  • Webpack dev server 顾名思义是为了开发目的......在生产中,你需要组装一个简单的服务器(即 Express 服务器......)
  • 是的,我知道开发服务器用于开发目的。一年前,我使用 react、redux 和 react-router 创建了另一个 Web 应用程序。不幸的是,我丢失了我的代码,但我很确定我没有在生产级别使用任何服务器我的服务器上仍然有处理整个应用程序的捆绑文件

标签: reactjs react-router react-router-dom


【解决方案1】:

我已经使用 HashRouter 解决了这个问题。 Router 存在一些安全问题,因此您必须在服务器上运行它,例如,如果您想使用它,则必须在 express 服务器上运行。

这是我更新的代码。对于历史,我使用历史中的 CreateHashHistory 函数。

import {
    HashRouter,
    Route,
    Switch
} from "react-router-dom";

<Provider store={store}>
    <HashRouter history={history}>
        <div>
            <Header />
            <Switch>
                <Route exact path="/" component={Login} />
                <Route exact  path="/login" component={Login} />
                <Route exact  path="/create/questions" component={CreateQuestion} />
                <Route exact  path="/create/quiz" component={CreateQuiz} />
            </Switch>
        </div>
    </HashRouter>
</Provider>

【讨论】:

    猜你喜欢
    • 2017-11-14
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2023-01-15
    • 2018-01-24
    • 2021-05-14
    • 2019-07-14
    • 2021-05-01
    相关资源
    最近更新 更多