可以使用browserHistory实现单页应用程序的反应吗?

时间:2017-01-09 18:32:01

标签: reactjs webpack react-router webpack-dev-server

我一直在使用来自hashHistory的{​​{1}}构建一个反应单页面应用,事情一直很好,直到我决定删除URL中的尾随代码,如下所示: react-router

我遇到的推荐解决方案是转换到browserHistory,但我注意到所有示例和解决方案都需要使用#/?_k=ncbx6v并将webpack-dev-server设置为true。我尝试了这种方法并且它有效(通过history-api-fallback),但曾经工作的独立的bundle.js文件+ index.html不再有效。

当我运行webpack并打开html文件时,我在控制台中收到此错误: localhost

我不熟悉问题背后的机制,但我很好奇是否有我不熟悉的解决方案。

这是我的webpack文件:

Warning: [react-router] Location "/Users/mike/project/index.html" did not match any routes

这是我的app.js:

const {resolve} = require('path')

module.exports = () => {
  return {
    context: resolve('src'),
    entry: './app',
    output: {
      path: resolve('public'),
      filename: 'bundle.js',
      publicPath: '/public/'
    },
    resolve: {
      extensions: ['.js', '.jsx', '.json']
    },
    stats: {
      colors: true,
      reasons: true,
      chunks: false
    },
    module: {
      rules: [
        {enforce: 'pre', test: /\.jsx?$/, loader: 'eslint-loader', exclude: [/node_modules/]},
        {test: /\.jsx?$/,loader: 'babel-loader', include: /src/, exclude: /node_modules/
        },
        {test: /\.json$/, loader: 'json-loader'},
        {test: /(\.css)$/, loaders: ['style-loader', 'css-loader']},
        {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader"},
        {test: /\.(woff|woff2)$/, loader: "url-loader?prefix=font/&limit=5000"},
        {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/octet-stream"},
        {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=image/svg+xml"}
      ]
    }
  }
}

1 个答案:

答案 0 :(得分:1)

要使用浏览器历史记录,您需要一个可以处理所有可能路由的路由的后端。如果您不打算拥有一个可以支持路由的后端(例如,您将提供静态文件),那么您应该坚持使用哈希历史记录。

浏览器历史记录工作原理的基本解释是它查看当前URL的pathname并尝试将其与已知路由进行匹配。在您收到的错误中,您的pathname/Users/mike/project/index.html。这意味着为了让React Router匹配该URL,您必须定义<Route> path(或者有一系列嵌套<Route> s)是/Users/mike/project/index.html

<Route path='Users/mike/project/index.html' component={App} />

散列历史记录与静态文件一起使用,因为它只是在pathname之后添加一个哈希符号,并在此之后确定路径。

如果您的问题只是您不喜欢使用查询密钥(?_k=jkadjlkd),则可以指定在create your history instance时不应包含该密钥。这些网址仍会包含#,但不再包含密钥&#34;垃圾&#34;附在他们身上。

import { Router, useRouterHistory } from 'react-router'
import { createHashHistory } from 'history'

const appHistory = useRouterHistory(createHashHistory)({ queryKey: false })
<Router history={appHistory} />
相关问题