React Router browserHistory适用于本地,而非生产

时间:2016-04-20 06:28:26

标签: javascript reactjs react-router

每当我在本地使用browserHistory时我都没有问题,但是当我在发货之前测试它时,我得到一个带有错误的空白页面。所以当我用hashHistory替换browserHistory时一切正常,但我丢失了漂亮的网址。

  

未捕获的SecurityError:无法在“历史记录”上执行“replaceState”:无法在具有origin的文档中创建具有URL“file:///Users/somefile/work/someproject/index.html”的历史状态对象null'和URL。

const Routes = (
  <Router history={browserHistory}>
    <Route path="/" component={Login} />
    <Route path="/content" component={App} >
      <Route path="/component1" component={component1} />
      <Route path="/component2" component={component2} />
      <Route path="/component3" component={component3} />
    </Route>
  </Router>
);

在我的index.js

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
const store = createStoreWithMiddleware(reducers);

ReactDOM.render(
  <Provider store={store}>
  {Routes}
  </Provider>,
  document.querySelector('.react-internal')
)

在我的app.js

export default class App extends Component {

  render() {
    return (
      <div>
      <Header />
      <div className="container-fluid">
        {this.props.children}
        </div>
      </div>
    );
  }
}

和我的webpack文件

var webpack = require('webpack');

module.exports = {
  devtool:'source-map',
  entry: [
    './src/index.js',
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        exclude: /node_modules/,
        loaders: ['react-hot','babel']
      },
      { test: /\.css$/, loader: "style!css" },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
            'file?hash=sha512&digest=hex&name=[hash].[ext]',
            'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  devServer: {
    port:8080,
    historyApiFallback: true,
    contentBase: './'
  }
};

2 个答案:

答案 0 :(得分:2)

我必须添加一个基本网址并链接到该文件夹​​。我认为这一切都取决于你如何部署

import { createHistory } from 'history'


const history = useRouterHistory(createHistory)({
  basename: '/projectFolder'
})
const Routes = (
  <Router history={history} >

    <Route path="/" component={Login} />
    <Route path="/content" component={App} >
      <Route path="/component1" component={component1} />
      <Route path="/component2" component={component2} />
      <Route path="/component3" component={component3} />
    </Route>
  </Router>
);

答案 1 :(得分:2)

此外,您还需要考虑部署项目的位置。例如,如果你部署到firebase,在firebase.json文件中你必须添加这个&#34; destination&#34;:&#34; /index.html"码。在包含这些代码行之后,url将正常工作

firebase.json

{
 "hosting": {       
   "public": "public/dist", 
   "rewrites": [ {
     "source": "**",   
     "destination": "/index.html"  // this line of code is very important, which makes your url work in production. This code means that no matter what url is, direct all processing in index.html
   } ]
 }

}