【问题标题】:React router v4, cannot find in routeReact路由器v4,在路由中找不到
【发布时间】:2017-04-18 15:04:46
【问题描述】:

我正在尝试使用反应路由器 v4。我使用的版本是 4.1.1。当页面加载时它会按原样呈现 Home 组件。但是如果我导航到localhost:8080/aboutlocalhost:8080/test2,我会在浏览器中看到这个

Cannot GET /about

我的App.jsx 文件:

import React  from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';

import Home from '../components/Home.jsx';
import Test from '../components/Test.jsx';

const Test2 = () => (
  <div>test2 component</div>
);

const App = (props) => (
  <BrowserRouter>
    <div className="container-fluid">
      <Route exact path="/" component={Home} />
      <Route path="/about" component={Test} />
      <Route path="/test2" render={Test2} />
    </div>
  </BrowserRouter>
)
export default App;

Webpack 配置:

const HtmlWebpackPlugin = require('html-webpack-plugin');

const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: '/node_modules/'},
      { test: /\.jsx$/, loader: 'babel-loader', exclude: '/node_modules/'}
    ]
  },
  plugins: [HtmlWebpackPluginConfig],
  devServer: {
    contentBase: './dist',
    historyApiFallback: true,
  }
};

【问题讨论】:

  • 问题出在您的服务器上。您使用的是webpack-dev-server 还是其他人。显示相关配置。
  • 是的,我已经编辑并包含了我的 webpack。是的,我正在使用 webpack-dev-server
  • 没有提到webpack-dev-server 你能展示你的 package.json 你是如何启动你的开发服务器的吗?
  • @Panther "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server" },跨度>
  • package.json中的start更改为webpack-dev-server --history-api-fallback,然后重新启动服务器。

标签: javascript reactjs react-router url-routing webpack-dev-server


【解决方案1】:

尝试将output.publicPath = '/' 添加到您的配置中。这是下面的示例 webpack 配置,它使用 ^ 并为我修复了刷新问题。如果您对“为什么”感到好奇,this 会有所帮助。

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'
    })
  ]
};

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 2018-03-13
    • 2017-11-05
    • 2016-07-03
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2017-12-16
    相关资源
    最近更新 更多