react-router v4中 HashRouter 和 BrowserRouter的使用

遇到的問題

項目中控制路由跳轉使用的是BrowserRouter,代碼以下:html

ReactDOM.render((
    <BrowserRouter>
        <div className="container">
            <Route path={routePaths.INDEX} exact component={Index} />
            <Route path={routePaths.CARD} component={Card} />
            <Route path={routePaths.BASEINFO} component={BaseInfo} />
            <Route path={routePaths.EDUINFO} component={EduInfo} />
            <Route path={routePaths.FAMILYINFO} component={FamilyInfo} />
            <Route path={routePaths.OTHERINFO} component={OtherInfo} />
            <Route path={routePaths.DETAIL} component={Detail}/>
        </div>
    </BrowserRouter>
    ),
    document.getElementById('app')
);

在開發過程當中使用是沒有問題的,可是將頁面上傳至服務器以後,問題就來了:用戶訪問的資源不存在,頁面是空白的。 通過排查懷疑是路徑的問題,將BrowserRouter 改成 HashRouter以後,問題解決了~react

問題分析

首先分析下出現此問題的緣由: 在React項目中咱們常常須要採用React-Router來配置咱們的頁面路由,React-Router 是創建在 history 之上的,常見的history路由方案有三種形式,分別是:webpack

  • hashHistory
  • browserHistory
  • createMemoryHistory

hashHistory 使用 URL 中的 hash(#)部分去建立路由,舉例來講,用戶訪問http://www.example.com/,實際會看到的是http://www.example.com/#/。git

<HashRouter>
        <div className="container">
            <Route path='/repos' component={Repos} />
            <Route path='/about' component={About} />
        </div>
    </HashRouter>

上面代碼中,用戶訪問/repos(好比http://localhost:8080/#/repos)時,加載Repos組件;訪問/about(http://localhost:8080/#/about)時,加載About組件。github

browserHistory 是使用 React-Router 的應用推薦的 history方案。它使用瀏覽器中的 History API 用於處理 URL,建立一個像example.com/list/123這樣真實的 URL 。web

在browserHistory 模式下,URL 是指向真實 URL 的資源路徑,當經過真實 URL 訪問網站的時候,因爲路徑是指向服務器的真實路徑,但該路徑下並無相關資源,因此用戶訪問的資源不存在。瀏覽器

Memory history 不會在地址欄被操做或讀取。這就解釋了咱們是如何實現服務器渲染的。同時它也很是適合測試和其餘的渲染環境(像 React Native )。和另外兩種history的一點不一樣是你必須建立它,這種方式便於測試。服務器

const history = createMemoryHistory(location)

解決辦法

  • 使用hashHistory

本地開發時,使用browserHistory是沒有問題的,這是由於webpack.config.js中使用 webpack-dev-server 已經作了配置。react-router

 webpackConfig.devServer = {
        contentBase: path.resolve(__dirname, 'build'),
        compress: true, //gzip壓縮
        historyApiFallback: true,
    };
  • 若是要使用browserHistory的話,服務器須要進行相關路由配置,方法見 這裏

參考資料:app

  1. https://www.sitepoint.com/react-router-v4-complete-guide/
  2. http://react-guide.github.io/react-router-cn/docs/guides/basics/Histories.html
  3. https://www.thinktxt.com/react/2017/02/26/react-router-browserHistory-refresh-404-solution.html
  4. http://echizen.github.io/tech/2016/07-05-webpack-dev-server-react-router-config
  5. https://jaketrent.com/post/pushstate-webpack-dev-server/
相關文章
相關標籤/搜索