如何在 Gatsby 中获取 URL 参数

3

我最近开始学习React和Gatsby。我的页面有一些URL参数,我该如何获取它并将其放入href属性中?在我的本地机器上一切都运行良好。但是在使用gatsby build后,我的变量url = undefined

import React from 'react';

const url = typeof window !== `undefined` ? window.location.search : ``;

const Article = ({
  content: {
    text,
    limit,
    rate,
    term,
    link,
    logo: {
      title,
      file: {
        URL,
      },
    },
  },
}) => {

  return (
    <Articles>
      <div>
        <button className="btn">
          <a href={url} target="_blank" rel="noreferrer" id="link-mfo">
            Получить деньги
          </a>
        </button>
      </div>
    </Articles>
  );
};
1个回答

4
你需要使用 useState 来存储这些数据,并在每次更改 href 属性时使它们可用。类似这样的代码应该可以解决问题:
import React, { useEffect, useState } from 'react';
    
const Article = ({
  content: {
    text,
    limit,
    rate,
    term,
    link,
    logo: {
      title,
      file: {
        URL,
      },
    },
  },
}) => {
  const [urlParams, setUrlParams] = useState(``);
  useEffect(() => {
    if(typeof window !==`undefined`){
      const queryString = window.location.search;
      const urlParams = new URLSearchParams(queryString);
      if(urlParams){
        setUrlParams(urlParams);
      }
    }
  }, []);

  return (
    <Articles>
      <div>
        <button className="btn">
          <a href={urlParams} target="_blank" rel="noreferrer" id="link-mfo">
            Получить деньги
          </a>
        </button>
      </div>
    </Articles>
  );
};

这基本上是useStateuseEffect钩子的经典组合。一旦DOM树加载完毕(空的deps,即[]),将触发获取URL参数的函数并将结果存储在setUrlParams中。最后,通过href={urlParams}将值传递给href属性。当然,你也可以找到其他解决方法。
const url = typeof window !== `undefined` ? window.location.search : ``;

将其设置为const,可以在服务器端渲染(SSR)中固定其值,因为这是gatsby build发生的地方,将其设置为undefined后就不再更新。


谢谢!这对我有用。但是,如果URL没有参数,我会得到null。我该如何检查变量url不为空?例如,我的链接:https://example.com/?null,我想从URL中删除此null,并仅在变量URL不为空时使用。 - Артём Данилов
将其包含在条件语句中:if(urlParams) setUrlParams(urlParams)。如果URL没有参数,则将采用useState()中设置的初始值(空字符串)。 - Ferran Buireu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接