[英]Window is not defined
我在我的项目中使用ReactJS,我想通过使用window.location.href来访问我当前的URL。 当我使用window.location.href时,我得到一个错误,说明窗口没有定义。
// --- REACT + CUSTOM-TAGS ---
const SampleApp = ({value}) => {
// --- CUSTOM-SCRIPTS ---
addMeta([
{type: 'meta', content: {content: 'something'}},
{type: 'link', content: {rel: 'http://link'}},
]);
//Append the value from the URL
const prId = "12512" //We can make it dynamic
const url = window.location.href;//window,location.href;
const id = url.substring(url.lastIndexOf('/') + 1);
const output = id.replace(/[a-zA-Z=]/g, '');
return (
<div>
<h1>Hello {value}</h1>
<hr />
<h2>{url} took from prId</h2>
<hr />
<h2><a className="redirect" href={'//www.check.com/prId/' + output} target="_blank">Click Here</a>
</h2>
</div>
);
};
位置在道具中,因为窗口未在React中定义。
只需执行this.props.location.pathname
而不是window.location.href
。
如果您记录道具,请提供更多信息。
安装此库npm install --save-dev --save-exact jsdom jsdom-global
然后将其import 'jsdom-global/register';
组件顶部import 'jsdom-global/register';
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.