我非常熟悉React.js但不熟悉Gatsby.
我想在Gatsby?
我非常熟悉React.js但不熟悉Gatsby.
我想在Gatsby?
您可以使用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>
);
然后您可以访问下一页中的prevPathfrom this.props.location.state。
完全归功于@soroushchehresa 的回答——这个答案只是建立在它之上的额外内容。
Gatsby 将在生产构建期间抛出错误,因为location在服务器端渲染期间不可用。您可以通过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服务器端渲染,所以我们可以挂钩它的locationprops。只有路由器组件才能获得该props,但我们可以使用@reach/router的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'
现在每个 Gatsby 页面组件都将获得之前的 url props:
const SomePage = ({ location }) => (
  <div>previous path is {location.state.prevUrl}</div>
);
你也可以考虑创建一个容器,储存状态的客户端和使用wrapRootElement或者wrapPageElement在这两个gatsby-ssr.js和gatsby-browser.js。
这些答案部分正确。如果您使用链接 api 设置状态,则该状态会保留在浏览器历史记录中。
因此,如果您从Page1to 开始,Page2则 egstate.prevUrl将正确设置为Page1 
但是,如果您转到Page3fromPage2然后返回浏览器,state.prevUrl则仍然Page1是 false。
我发现处理这个问题的最好方法是在 gatsby-browser.js 上添加这样的东西
export const onRouteUpdate = ({ location, prevLocation }) => {
  if (location && location.state)
    location.state.referrer = prevLocation ? prevLocation.pathname : null
}
这样,您将始终可以在位置上找到以前的网址。
我用下面的代码解决了我的问题。这是参考链接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从任何地方访问。