【问题标题】:React Router not working correctly反应路由器无法正常工作
【发布时间】:2017-11-09 15:15:42
【问题描述】:

我是新手,不知道为什么这不起作用。

我的路由器代码在这里:

import React from 'react';  
import { Route, IndexRoute } from 'react-router'; 

import App from './components/App';  
import HomePage from './components/home/HomePage';  

export default (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage} />
    <Route path="example" component={HomePage} />
  </Route>
);

那么这段代码会发生什么:

localhost/ 显示正常

localhost/example 不显示

显示主页标题中的 localhost/example 链接,但按刷新不显示

感谢您的帮助,不胜感激!

这是我的 webpack 配置:

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

module.exports = {
  context: path.join(__dirname, "/client"),
  entry: [
    'webpack-dev-server/client?http://127.0.0.0:5000/',
    'webpack/hot/only-dev-server',
    'react-hot-loader/patch',
    './src/index.js'
  ],
  output: {
    path: path.join(__dirname, "/client/dist"),
    filename: '[name].js',
    publicPath: '/'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  devServer: {
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [ 'babel-loader', 'react-hot-loader/webpack' ],
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './static/template.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ]
};

app.js sn-p:

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(__dirname + 'client/dist'));
app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    historyApiFallback: true,
    stats: {
        colors: true
    }
}));

我正在使用 localhost:5000 。链接的问题没有解决我的问题

【问题讨论】:

  • 查看重复的问题。我相信这会解决你的问题
  • @ShubhamKhatri 没有用,还有其他建议吗?我已经编辑了
  • 你是从服务器上为你的 React 应用程序提供服务吗,在这种情况下,你可以试试这个https://www.npmjs.com/package/express-history-api-fallback

标签: reactjs react-router react-redux router


【解决方案1】:

仅供参考,从 4.0 版开始,React Router 不再使用 IndexRoute。

也为您的路径,将"example" 更改为"/example"

【讨论】:

  • OP 没有说他使用 React 路由器 v4,如果localhost/example link from the header on the homepage displays, but pressing refresh does not 行显示他没有使用 v4,否则它根本不会工作
猜你喜欢
  • 2019-06-17
  • 1970-01-01
  • 2017-03-15
  • 2020-08-26
  • 2019-05-08
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
相关资源
最近更新 更多