gpt4 book ai didi

javascript - 在 Gatsby 中获取 url 参数

转载 作者:行者123 更新时间:2023-12-04 08:37:03 25 4
gpt4 key购买 nike

我最近开始学习 React 和 Gatsby。我的页面有一些 URL 参数,我如何获取它并放入 href attr?一切都在我的本地机器上运行。但是在 gatsby 构建我的变量 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 Hook 的经典组合。一旦加载了 DOM 树(空 deps[]),获取 URL 参数的函数就会被触发并将结果存储在 setUrlParams 中。最后,您通过 href={urlParams} 传递 href 属性中的值。当然,您可以找到其他解决方法。

你的声明:

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

设置为const,固定SSR中的值(Server-Side Rendering),因为 gatsby build 发生在 undefined 并且从未更新过。

关于javascript - 在 Gatsby 中获取 url 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64755556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com