06月27, 2016

React HashHistory url参数问题

问题描述

在引用

import {Route,Router,hashHistory,useRouterHistory} from "react-router"

时,浏览器的url会自动生成一个params,如同:

localhost:8080/about?_key23423

这是为了兼容低版本的浏览器不支持browserhistory的做法,但是在url中会觉得好像getpost了某个参数。 官方的解释是:

The URLs in our app right now are built on a hack: the hash. Its the default because it will always work, but there's a better way.(better way说的是browserHistory)

解决方案:

如果要坚持使用hashHistory这种做法定义路由又不想要hash值,可以自定义history把后面的hash值去掉,做法如下:

import React from "react"
import { render } from "react-dom"

import {Route,Router,hashHistory,useRouterHistory} from "react-router"

import {createHashHistory} from "history"
import App from "./modules/App"
import About from "./modules/About.js"
import Repos from "./modules/Repos.js"

const appHashHistory = useRouterHistory(createHashHistory)({queryKey: false});
render((
   <Router history={appHashHistory}>
        <Router path="/" component={App}>
            <Router path="/about" component={About}></Router>
            <Router path="/repos" component={Repos}></Router>
        </Router>
    </Router>
),document.getElementById("app"));

参考链接

https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#using-custom-histories

本文链接:https://beacelee.com/post/react-hashhistory-url.html

-- EOF --

Comments

评论加载中...

注:如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理。