在盖茨比获取url参数



我最近开始学习React和Gatsby。我的页面有一些URL参数,如何获取并放入href属性?在我的本地机器上一切正常。但是在盖茨比建立了我的变量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>
);
};

您需要使用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中的值(Server-SideRendering(固定为undefined,因为这是gatsby build发生的地方,从未更新。

最新更新