从查询字符串重定向到路径

Redirection from a query string to a path

我目前正在更新旧版应用程序的前端,该前端使用查询参数作为 "path"。 (例如:?greeting=hello 而不是 /greeting/hello

无论如何向前推进,我们希望过渡到基于路径的路由,并从旧查询结构重定向。

最好我喜欢做这样的事情:

<Redirect from="?gameid=:game" to="/game/:game" />

然而,它似乎并不那么简单,因为 react-router 不提供对查询参数的支持 (#209)。

解决这个问题最干净的方法是什么?

URL 使用普通 JS 的操作已被证明与 react 结合时非常容易出错。

原来我的情况是一个非常极端的情况,因此 react-router 不能很好地处理。

由于应用程序使用基于哈希的历史记录 (/#/path),如果查询参数没有在 onEnter 的 [=13= 中以哈希开头,它们将不会被捕获].

我最终做的是在 IndexRouter.

中处理任何可能的查询
<IndexRoute component={LoginPage}
  onEnter={
    (nextState, replaceWith) => {
      console.log(nextState);
      var obj = qs.parse(document.location.search.split("").slice(1,document.location.search.split("").length).join(""));
      if(obj.gameid){
        document.location.href = document.location.origin + document.location.pathname + "#/game/" + obj.gameid;
      }
    }
  }
/>

这种方式似乎比将路由逻辑放在容器应用程序的 componentDidMount 中更可取,因为路由逻辑实际上属于 Route 的内部。它还确保所有后续调用 得到正确处理。

感谢 /u/mrkre 为我指明了 onEnter 的方向。