【问题标题】:Angular to React - How to replace use of pound sign (hashtag)Angular to React - 如何替换井号(标签)的使用
【发布时间】:2017-06-16 18:50:30
【问题描述】:

我即将重做从 Angular 1 到 React 的代码切换。我使用React Boilerplate 有一段时间了,它使用 React Router v3,我真的很喜欢这个设置。我的 Angular 项目使用像 example.com/#/about 这样的 URL,我真的不喜欢 # 符号的概念,所以我想让 URL 看起来像 example.com /关于

问题是一些 URL 已经公开,所以我希望它们能够向后兼容。例如,如果用户转到 /#/about,那么他们将被自动重定向到 /about

如果您了解 React Boilerplate 的生态系统,那将会很有帮助。我知道重定向的概念很简单,但我想在样板文件中以一种干净的方式做到这一点。有什么想法吗?

谢谢!

【问题讨论】:

  • 这在 react-router v3 文档中有非常清楚的记录:github.com/ReactTraining/react-router/blob/v3/docs/guides/…
  • 感谢您的链接。我从来没有遇到过这个,这是一个开始,但是 React Boilerplate 也使用 react-router-redux 并且路由的声明方式不同。我将继续尝试解决这个问题,但如果有人可以在 React Boilerplate 方面提供帮助,将不胜感激。

标签: javascript reactjs react-router react-boilerplate


【解决方案1】:

感谢@Calvin 上面的评论,它让我有了不同的思考过程。我发现 React Boilerplate 允许这样的重定向:

onEnter: (_nextState, replace, next) {
    replace('/something');
    next();
}

这将被放置在 routes.js 文件中。我找到此答案的问题/答案的链接是here

编辑

确切的答案最终是这个函数:

const sniffHash = (nextState, replace, next) => {
    if (nextState.location.hash !== '') {
        let path = nextState.location.hash.replace('#', '');
        replace(path);
    }
    next();
}

我在家乡路线上使用了变量名,如下所示:

path: '/',
name: 'home',
onEnter: sniffHash,
getComponent(nextState, cb) {
    //React Boilerplate router stuff
}

唯一需要注意的是,如果我需要锚链接,那么我必须弄清楚一些事情。不理想,但它可能对必须进行此类过渡的人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2018-12-16
    • 2021-08-01
    • 2016-03-22
    • 2020-06-03
    相关资源
    最近更新 更多