我对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>
);
然后,您可以在下一页访问prevPath
的this.props.location.state
。
完全归功于@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
组件将其传递给其他组件。
有了它,我们可以编写一个自定义链接组件,它始终在其状态中传递前一个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 }
然后我们可以导入我们的自定义链接组件而不是Gatsby的链接:
- import { Link } from 'gatsby'
+ import { Link } from './link-with-prev-url'
现在每个Gatsby页面组件都会获得以前的url道具:
const SomePage = ({ location }) => (
<div>previous path is {location.state.prevUrl}</div>
);
您可能还会考虑创建一个容器来存储客户端的状态,并在wrapRootElement
和wrapPageElement
中使用gatsby-ssr.js
或gatsby-browser.js
。