【问题标题】:Remove Hashbang from url using redux-router使用 redux-router 从 url 中删除 Hashbang
【发布时间】:2016-04-08 01:07:26
【问题描述】:

Hashbang(#!) 在使用 react-router 时被附加到 url。

例如:http://localhost:3000/#!/?

示例代码:

import React from 'react';
import { combineReducers, applyMiddleware, compose, createStore } from 'redux';
import { reduxReactRouter, routerStateReducer, ReduxRouter } from 'redux-router';
import { createHistory } from 'history';
import { Route } from 'react-router';

const routes = (
   <Route path="/" component={App}>
    <Route path="parent" component={Parent}>
    <Route path="child" component={Child} />
    <Route path="child/:id" component={Child} />
   </Route> );

   const reducer = combineReducers({
    router: routerStateReducer,
   });

   const store = compose(
    applyMiddleware(m1, m2, m3),
    reduxReactRouter({
    routes,
    createHistory
   }),
   devTools()
   )(createStore)(reducer);

如何从 URL 中删除 Hashbang?

【问题讨论】:

  • 我认为你的意思是 react-router,因为 redux-router 只是其中的一个层。并请注明版本。
  • 您将无法更改此行为,因为这是 react 路由器的工作方式。它正在侦听 HashChange 事件以识别您的 URL 中的更改。
  • 反应路由器:1.0.0-rc3,redux路由器:1.0.0-beta5

标签: reactjs react-router react-router-redux


【解决方案1】:

我假设你想一起摆脱散列网址(hashbang 也有 !)。

按照此处的说明进行操作:

https://github.com/rackt/react-router/blob/latest/docs/guides/basics/Histories.md#browserhistory

他们向您展示了一个使用 Express 的示例(尽管几乎可以使用任何服务器):

const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()

// serve static assets normally
app.use(express.static(__dirname + '/public'))

// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})

app.listen(port)
console.log("server started on port " + port)

我建议确保说明正确,将 react-router 更新为 2.0.0-rc4,尽管乍一看,指南的这一部分似乎仍然适用,无需更改。

本质是您的服务器首先捕获对真实物理文件的请求,然后将任何剩余的 GET 请求发送到index.html

server-side rendering 有一个更高级的方法,请求通过路由器传递,但我暂时忽略它。

那么在客户端你应该使用browserHistory:

import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, IndexRoute } from 'react-router'

import App from '../components/App'
import Home from '../components/Home'
import About from '../components/About'
import Features from '../components/Features'

render(
  <Router history={browserHistory}>
    <Route path='/' component={App}>
      <IndexRoute component={Home} />
      <Route path='about' component={About} />
      <Route path='features' component={Features} />
    </Route>
  </Router>,
  document.getElementById('app')
)

【讨论】:

  • Dominic 感谢您提供的信息。实际上这是我的错误,我使用“qs”包将一些东西附加到 url。它正在制造问题。
猜你喜欢
  • 2019-02-11
  • 2016-11-04
  • 2018-09-16
  • 2022-09-22
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 2017-05-11
  • 2022-11-19
相关资源
最近更新 更多