如何在React Gatsby中获取先前的URL

时间:2019-03-01 09:53:13

标签: javascript reactjs gatsby static-site

我对React.js非常熟悉,但对Gatsby还是陌生的。

我要检测Gatsby中的上一页URL?

4 个答案:

答案 0 :(得分:7)

您可以使用Link组件传递状态:

import React from 'react';
import { Link } from 'gatsby';

const PrevPage = () => (
  <div>
    <Link
      to={`/nextpage`}
      state={{ prevPath: location.pathname }}
    >
      Next Page
    </Link>
  </div>
)

const NextPage = (props) => (
  <div>
    <p>previous path is: {props.location.state.prevPath}</p>
  </div>
);

然后您可以从下一页的prevPath访问this.props.location.state

答案 1 :(得分:4)

@soroushchehresa's answer的信任,这是在此基础上的补充。

由于location在服务器端渲染期间不可用,因此Gatsby将在生产构建期间引发错误。您可以通过首先检查window对象来解决它:

class Page extends React.Component {
  state = {
    currentUrl: '',
  }

  componentDidMount() {
    if (typeof window == 'undefined') return
    this.setState({ currentUrl: window.location.href })
  }

  render() {
    return (
      <Link to="..." state={{ prevUrl: this.state.currentUrl }}>
    )
  }
}

但这需要我们在每个页面上实现,这很繁琐。 Gatsby已经为服务器端渲染设置了@reach/router,因此我们可以加入其location道具。只有路由器组件才能获得该道具,但是我们可以使用@reach/router's Location组件将其传递给其他组件。

有了这一点,我们可以编写一个自定义Link组件,该组件始终以其状态传递先前的url:

// ./src/components/link-with-prev-url.js

import React from 'react'
import { Location } from '@reach/router'
import { Link } from 'gatsby'

const LinkWithPrevUrl = ({ children, state, ...rest }) => (
  <Location>
    {({ location }) => (
                      //make sure user's state is not overwritten
      <Link {...rest} state={{ prevUrl: location.href, ...state}}>
        { children }
      </Link>
    )}
  </Location>
)

export { LinkWithPrevUrl as Link }

然后,我们可以导入自定义的Link组件而不是Gatsby的Link:

-  import { Link } from 'gatsby'
+  import { Link } from './link-with-prev-url'

现在,每个盖茨比页面组件都将获得以前的网址道具:

const SomePage = ({ location }) => (
  <div>previous path is {location.state.prevUrl}</div>
);

您还可以考虑创建一个存储客户端状态的容器,并在gatsby-ssr.jsgatsby-browser.js中使用wrapRootElementwrapPageElement

答案 2 :(得分:3)

这些答案部分正确。如果您使用链接api设置状态,则该状态会保留在浏览器历史记录中。

因此,如果您从Page1转到Page2,则state.prevUrl例如将正确设置为Page1

但是,如果您从Page3转到Page2,然后返回浏览器,则state.prevUrl仍然是Page1,这是错误的。

我发现最好的解决方法是在gatsby-browser.js上添加类似的内容

export const onRouteUpdate = ({ location, prevLocation }) => {
  if (location && location.state)
    location.state.referrer = prevLocation ? prevLocation.pathname : null
}

这样,您将始终在位置上获得以前的URL。

答案 3 :(得分:0)

我用下面的代码解决了我的问题。这是参考链接 https://github.com/gatsbyjs/gatsby/issues/10410

// gatsby-browser.js
exports.onRouteUpdate = () => {
  window.locations = window.locations || [document.referrer]
  locations.push(window.location.href)
  window.previousPath = locations[locations.length - 2]
}

现在您可以从任何地方访问previousPath