【问题标题】:React Router not working when URL contains multiple paths当 URL 包含多个路径时,React Router 不起作用
【发布时间】:2019-07-14 03:13:02
【问题描述】:

我正在使用 webpack-dev-server 进行开发并同样响应路由器。这是我的 wepack 配置。

const webpack = require('webpack');
const path = require('path');
const common = require('./common.config.js')
const merge  = require('webpack-merge')

const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin')

module.exports = merge(common, {
    devtool: 'source-map',
    mode:'development',
    module: {
        rules: [
           {
                test: /\.(sa|sc|c)ss$/,
            use: [
                       {
                  // Adds CSS to the DOM by injecting a `<style>` tag
                  loader: 'style-loader'
                       },
                       {
                          // Interprets `@import` and `url()` like `import/require()` and will resolve them
                          loader: 'css-loader'
                   },
                   {
                          // Loader for webpack to process CSS with PostCSS
                          loader: 'postcss-loader',
                          options: {
                          plugins: function () {
                                return [
                                require('autoprefixer')
                                ];
                                   }
                          }
                       },
               {
                  // Loads a SASS/SCSS file and compiles it to CSS
                  loader: 'sass-loader'
               }
                 ]
           }
        ]
    },
    devServer:{
       contentBase: path.join(__dirname, '../dist'),
       port: 3000,
       proxy:{
          '/api': 'http://127.0.0.1:5000',
       },
       historyApiFallback:true,
       overlay: true,
       stats: 'normal'
    },
    watchOptions: {
       ignored: /node_modules/
    },

    plugins: [
    new CleanWebpackPlugin(['../dist'], { exclude:['sw.js']}),
        new HtmlWebpackPlugin({
            title: 'Script App - Dev',
            filename: '../dist/index.html',
        template:'index_template.html'
        }),
    new MiniCssExtractPlugin({
            filename: 'bundled_styles.css'
        }),
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()    
    ],
});

这是我的应用程序的入口点(我已经定义了路线)

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import {BrowserRouter, Route, Switch} from 'react-router-dom'

import configureStore from './store/configureStore';

import FirstComponent from './FirstComponent';
import SecondComponent from './SecondComponent';
import App from './App';

const store = configureStore();

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
            <App>
               <Switch>
                   <Route path="/first/:a_code" component={FirstComponent} />
                   <Route path="/second" component={SecondComponent} />
               </Switch>
            </App>
        </BrowserRouter>
    </Provider>,

    document.getElementById('root')
);

我正在使用 react-router v4wepack v4.29

我的问题:当我使用 history 属性从我的代码中推送路由时,一切正常,但是当我用路由刷新浏览器时,一切都变为空白。 只有在具有多条路径的路由中才会出现这种行为(/first/:param)。

我尝试过的事情:我从一些 SO 帖子中读到,我必须将我的 webpack 配置中的 historyApiFallback 属性设置为 true,我做到了,但它仍然没有帮助. this github issue 中的一个 cmets 表示,如果 webpack 配置中提供了某些 proxy 配置,historyApiFallback 将无法正常工作。

我不想删除这些 proxy 配置,因为我正在对运行在不同端口上的另一台服务器进行 api 调用。

谁能帮我解决这个问题?请!

【问题讨论】:

  • 您能否举例说明路线在地址栏中的外观?
  • @RRK 这里是一个路由示例:localhost:3000/first/rt
  • 只是一个预感,你可以试试不带下划线的参数名吗?例如:a_code:acode
  • @RRK 我怀疑这是否是问题所在,因为我之前使用了不带下划线的不同变量名,但它没有解决问题。

标签: reactjs webpack react-router


【解决方案1】:

我也遇到过类似的情况,我使用 render: func 解决了,这样可以避免在位置匹配时重新安装组件。

所以我的路线看起来像这样

<Route
  path="/first/:a_code"
  render={props => 
    <FirstComponent {...props}/>
  }
/>

然后在我的组件中我得到匹配的参数

const first_component = (props) => {
  return (
    <div>
      {props.match.params.a_code}
    </div>
  )
}

在 url "/first/something" 处,我可以刷新浏览器并仍然获得所需的参数,并且没有任何错误或空白页面。而且我不相信这是配置问题,因为到目前为止我还没有弹出这个项目中的 webpack 配置。

【讨论】:

    【解决方案2】:

    我实际上错过了一个 webpack 配置。我必须添加一个output 配置并将publicPath 设置为/。即

    output:{
      publicPath: '/'
    }
    

    我还在devServer 配置中添加了publicPath。即

    devServer:{
      ...
      publicPath:'/',
      historyApiFallback: true
    }
    

    更新:

    同样确保您的 bundle.js 脚本插入到您的 html 文件中,如下所示:

    <script src="/bundle.js"></script>
    

    与否

    &lt;script src="./bundle.js"&gt;&lt;/script&gt;&lt;script src="bundle.js"&gt;&lt;/script&gt;

    【讨论】:

    • 这对我有用。同样对于未来的人们,在支持现代 HTML5 的浏览器中,假设您无权访问 webpack 配置文件,或者您只支持现代浏览器,将 &lt;base href="/"&gt; 添加到 index.html 文件的标题部分也可以
    • devServer{} 中的 publicPath 对我没有任何影响,但我的 html 文件中的 bundle.js 引用完全解决了这个问题。现在完美运行
    猜你喜欢
    • 1970-01-01
    • 2015-07-12
    • 2021-10-15
    • 2016-05-07
    • 1970-01-01
    • 2018-04-05
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多