首页 文章

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

提问于
浏览
0

我一直在使用来自react-routerhashHistory建立一个反应单页应用程序,并且事情一直很好,直到我决定删除 URL 中的尾随代码,如下所示:#/?_k=ncbx6v

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

当我运行 webpack 并打开 html 文件时,我在控制台中收到此错误:Warning: [react-router] Location "/Users/mike/project/index.html" did not match any routes

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

这是我的 webpack 文件:

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"}
      ]
    }
  }
}

这是我的 app.js:

'use strict'
import React from 'react'
import ReactDOM from 'react-dom'
import Layout from './components/common/Layout'
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import configureStore from './store/configureStore'
import { Provider } from 'react-redux'

const store = configureStore()

class App extends React.Component {
  render () {
    return (
      <Provider store={store}>
        <Router history={browserHistory}>
          <Route path='/' component={Layout}></Route>
        </Router>
      </Provider>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'))

1 回答

  • 1

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

    浏览器历史记录工作原理的基本解释是它查看当前 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),则可以指定在创建历史实例时不应包含该查询键。 URL 仍将包含#,但不再附加密钥“垃圾”。

    import { Router, useRouterHistory } from 'react-router'
    import { createHashHistory } from 'history'
    
    const appHistory = useRouterHistory(createHashHistory)({ queryKey: false })
    <Router history={appHistory} />
    

相关问题