我在我的项目中使用ReactJS,我想通过使用window.location.href来访问我当前的网址。当我使用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>
);
};发布于 2017-05-03 23:04:04
位置在道具中,因为窗口没有在React中定义。
只需执行this.props.location.pathname而不是window.location.href。
更多的信息,如果你记录道具。
发布于 2018-02-27 04:44:16
安装这个库npm install --save-dev --save-exact jsdom jsdom-global,然后将它导入到您的组件顶部import 'jsdom-global/register';希望它能有所帮助。
https://stackoverflow.com/questions/43763367
复制相似问题