ReactJS URL查询字符串。 BrowserHistory无法正常工作

时间:2016-01-21 14:27:32

标签: javascript reactjs browser-history

我对react-router构建URL的方式有疑问。目前,URL为我提供了页面结构:

根组件:
http://localhost:3000/#/?_k=24zils
联系组件:
http://localhost:3000/#/contact?_k=v12iev
关于组件:
http://localhost:3000/#/about?_k=b22bqm

我试图让它们显示如下:

根组件:
http://localhost:3000/#/
联系组件:
http://localhost:3000/#/contact
关于组件:
http://localhost:3000/#/about

我正在阅读react-router支持的browserHistory。它使用浏览器中内置的History API来操作URL。

路由器文件:

//Import Dependencies.
import React from 'react';
import { Router, Route } from 'react-router'
import ReactDOM from 'react-dom';

//Import Components.
import HomeElement from '../views/home/home.jsx';
import ContactElement from '../views/contact/contact.jsx';
import AboutElement from '../views/about/about.jsx';

//Set up routes.
let routes = (
    <Router>
        <Route path='/' component={HomeElement}/>
        <Route path='/about' component={AboutElement}/>
        <Route path='/contact' component={ContactElement}/>
    </Router>
);

export default routes;

主要文件:

//Import Dependencies.
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router'

//Import Routes.
import routes from './routes/routes.js';

ReactDOM.render(<Router history={browserHistory} routes={routes} />, document.getElementById('component-wrapper'));

我收到零错误。仍使用查询参数构建网址。关于我做错了什么的任何想法?

服务器

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');

new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true
}).listen(3000, 'localhost', function (err, result) {
    if (err) {
        console.log(err);
    }
    console.log('Listening at localhost:3000');
});

1 个答案:

答案 0 :(得分:0)

使用react-router的哈希历史记录时,您可以将queryKey选项设置为false以禁用此行为,即使不建议这样做。

import React from 'react'
import ReactDOM from 'react-dom'
import { Router } from 'react-router'
import createHistory from 'history/lib/createHashHistory'

import routes from './routes/routes.js'

var history = createHistory({ queryKey: false })

ReactDOM.render(
  <Router history={history} routes={routes} />,
  document.getElementById('component-wrapper')
)

有关此here

的详细信息