React-router v4 - 无法获取 *url*

2023-12-22

我开始使用react-router v4。我有一个简单的<Router>在我的 app.js 中带有一些导航链接(请参阅下面的代码)。如果我导航到localhost/vocabulary,路由器将我重定向到正确的页面。但是,当我之后按重新加载(F5)时(localhost/vocabulary),所有内容消失并浏览器报告Cannot GET /vocabulary。这怎么可能?有人可以告诉我如何解决这个问题(正确重新加载页面)吗?

App.js:

import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { Switch, Redirect } from 'react-router'
import Login from './pages/Login'
import Vocabulary from './pages/Vocabulary'

const appContainer = document.getElementById('app')

ReactDOM.render(
  <Router>
    <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/vocabulary">Vocabulary</Link></li>
        </ul>
        <Switch>
          <Route exact path="/" component={Login} />
          <Route exact path="/vocabulary" component={Vocabulary} />
        </Switch>
    </div>
  </Router>,
appContainer)

我假设您正在使用 Webpack。如果是这样,在 webpack 配置中添加一些内容应该可以解决问题。具体来说,output.publicPath = '/' and devServer.historyApiFallback = true。下面是一个示例 webpack 配置,它使用了 ^ 并为我修复了刷新问题。如果你好奇“为什么”,this https://stackoverflow.com/questions/27928372/react-router-urls-dont-work-when-refreshing-or-writting-manually会有帮助的。

var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index_bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      { test: /\.(js)$/, use: 'babel-loader' },
      { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
    ]
  },
  devServer: {
    historyApiFallback: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'app/index.html'
    })
  ]
};

我在这里写了更多相关内容 -修复使用 React Router 刷新时的“cannot GET /URL”错误(或客户端路由器的工作方式) https://tylermcginnis.com/react-router-cannot-get-url-refresh/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React-router v4 - 无法获取 *url* 的相关文章

随机推荐