如何获得以前的网址反应盖茨比

问题描述 投票:2回答:2

我对React.js非常熟悉,但对Gatsby不熟悉。

我想检测Gatsby中的上一页网址?

javascript reactjs gatsby static-site
2个回答
9
投票

您可以使用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>
);

然后,您可以在下一页访问prevPaththis.props.location.state


4
投票

完全归功于@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>
);

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

© www.soinside.com 2019 - 2024. All rights reserved.