【问题标题】:Is there a way to programatically switch to hashHistory from browserHistory when on a webpack dev server?在 webpack 开发服务器上,有没有办法以编程方式从浏览器历史记录切换到 useHistory?
【发布时间】:2016-08-27 23:46:56
【问题描述】:

在使用 webpack-dev-server 时,有没有办法在 React Router 中自动从 browserHistory 切换到 hashHistory?如果页面刷新,我经常会收到 cannot GET/routename 错误。我可以通过手动切换到 hashHistory 来解决这个问题,但我想知道是否有一种好方法可以根据我是在开发还是生产环境自动来回切换。

我的 webpack.prod.config.js

const config = require('./webpack.config.js');
const webpack = require('webpack');

config.plugins.push(
  new webpack.DefinePlugin({
    "process.env": {
      "NODE_ENV": JSON.stringify("production")
    }
  })
);

config.plugins.push(
  new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false
    }
  })
);

module.exports = config;

我的路由器

render((
  <Router history={browserHistory}>
    {/** ###### HOME ROUTE ###### */}
    <Route path="/" component={Home} />
    <Route path="/company" component={Company} />
    <Route path="/help" component={Help} />
    <Route path="/features" component={Features} />
    <Route path="/signup" component={SignUp} />
    <Route path="/work" component={Work} />
    {/** ###### END HOME ROUTES ###### */}
  </Router>
), document.getElementById('root'));

【问题讨论】:

    标签: reactjs webpack react-router


    【解决方案1】:

    您可以在设置历史记录之前检查您的 NODE_ENV 变量,类似这样

    import { Router, Route, browserHistory,hashHistory IndexRoute } from 'react-router'
    
    let history = process.env.NODE_ENV === "production" ? browserHistory : hashHistory;
    
    
    render((
      <Router history={history}>
        {/** ###### HOME ROUTE ###### */}
        <Route path="/" component={Home} />
        <Route path="/company" component={Company} />
        <Route path="/help" component={Help} />
        <Route path="/features" component={Features} />
        <Route path="/signup" component={SignUp} />
        <Route path="/work" component={Work} />
        {/** ###### END HOME ROUTES ###### */}
      </Router>
    ), document.getElementById('root'));
    

    【讨论】:

      猜你喜欢
      • 2010-09-08
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多