【问题标题】:How to prevent react-router adding # to url?如何防止react-router将#添加到url?
【发布时间】:2016-07-24 01:22:12
【问题描述】:

正如标题所说,我怎样才能防止在 url 末尾添加 #。

routes.jsx

(export default (withHistory, onUpdate) => {
 const history = withHistory?
              (Modernizr.history ?
                browserHistory
              : hashHistory)
            : null;
return (
<Router history={history} onUpdate={onUpdate}>
  <Route path='/' component={App}>
    <IndexRoute component={quotes} />
    <Route path='/app/search' component={SimpleSearch} />

    <Route path='pathName' component={Blank1} />
      <Route path='pathName/:category' component={Blank1}/>
      <Route path='pathName/:category(/:page)' component={Blank1}/>
    <Route path='app/:id' component={Blank1} />

  </Route>

</Router>

);
};

blank1.jsx 中的方法

method(current,previous){
    const category= this.props.params.category;
    const page = current;
    const path = `/pathName/${category}/${page}`;
    browserHistory.push(path);
...
}

我尝试了很多方法,但没有 # 就无法获得链接。 它将 # 添加到末尾并不断触发我使用 this.setState 更改状态的 componentWillReceiveProps。而且在导航中,由于#

,所有导航项都没有处于活动状态

【问题讨论】:

  • 你应该使用 browserHistory 来获取没有哈希的 url

标签: reactjs redux react-router


【解决方案1】:

您指的是clean URLS。

您想使用browserHistory 而不是hasHistory/

然后您需要在您的服务器中添加一个* 路由,以便所有请求都通过 React Router 路由。

在你的服务器路由的末尾是这样的:

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'public', 'index.html'))
});

欲了解更多信息,请查看this example

【讨论】:

  • 在我的 server.js 中有 app.get('*', function(req, res, next) { renderHTML(req, res, next); });
猜你喜欢
  • 2017-01-16
  • 2019-02-26
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 2019-08-03
  • 2018-01-19
  • 2018-08-01
  • 1970-01-01
相关资源
最近更新 更多