React-redux 获取站点基础 URL / window.location

React-redux get site base URL / window.location

希望这是一个非常简单的问题:

我想创建一个包含完整 URL 到我网站页面的字符串,例如:

https://example.com/documents/1

理想情况下,我想在 mapStateToProps() 中的 react-redux connect()ed 容器中生成它。该页面是使用 browserHistory 的 react-router Route 的孙子页面(所以也许我可以通过某种方式从 react-router 或 browserHistory 获取它?)如果有必要,我会在完整的 React [=35 中进行=].

但我一辈子都不知道如何做到这一点。 window(在 window.location 中)在 mapStateToProps() 中总是 undefined(这并不奇怪),在我看来组件的 render() 函数。

到目前为止,我只找到了访问当前路线的方法,例如“/documents/1”,这只是一个相对路径,不包含站点基础url (https://example.com/)

所以首先,请记住您的代码在客户端和服务器上运行,因此对 window 的任何访问都需要包含在检查中。

  if (typeof window !== 'undefined') {
    var path = location.protocol + '//' + location.host + '/someting'; // (or whatever)
  } else {
    // work out what you want to do server-side...
  }

如果您生成的 URL 显示在 DOM 中,并且在客户端上您在第一次渲染之前使用此 URL 填充商店,您将获得校验和错误。如果你真的想避免这个错误,你可以等到 componentDidMount() 在你的根组件中 get/set url.

在componentDidMount之后你可以直接访问origin位置,这样你就可以获得root url。

我一直在我的 JSX 中使用以下代码,这样我就不必担心根路径,例如:dev env 这将是 localhost:3000/whatever,staging 这将是 AppStaging.heroku/whatever/..... 和在生产中它将评估为 www.myapp.com/whatever

`${window.location.origin.toString()}/whateverRoute/`

你可以试试!!

window.location.origin