【问题标题】:ReactJS URL Query String. BrowserHistory not workingReactJS URL 查询字符串。浏览器历史不工作
【发布时间】:2016-01-21 14:27:32
【问题描述】:

我对 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'));

我收到零错误。 Url 仍然使用查询参数进行结构化。关于我做错了什么有什么想法吗?

服务器:

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

【问题讨论】:

    标签: javascript reactjs browser-history


    【解决方案1】:

    在使用 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

    【讨论】:

    • 这会禁用状态,对吧?这不是我想要的。
    • 这是在使用 HashHistory 时摆脱查询参数的唯一方法。但是在您的情况下哈希是强制性的还是您想使用 BrowserHistory?
    • 我不想使用 hashHistory。这就是我尝试设置 browserHistory 的原因。知道为什么它不起作用吗?
    • 在您完成react-router docs 中提到的更改以处理新的历史行为后,您是否重新启动了服务器?
    • 我刚刚尝试重新启动我的服务器。仍然在 URL 中接收查询参数。
    猜你喜欢
    • 2013-04-02
    • 1970-01-01
    • 2011-04-05
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多