完全归功于@soroushchehresa's answer——这个答案只是建立在它之上的额外内容。
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,所以我们可以挂钩它的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'
现在每个 Gatsby 页面组件都会得到这个之前的 url 属性:
const SomePage = ({ location }) => (
<div>previous path is {location.state.prevUrl}</div>
);
您也可以考虑为客户端创建一个存储状态的容器,并在gatsby-ssr.js 和gatsby-browser.js 中使用wrapRootElement 或wrapPageElement。