首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未定义窗口

未定义窗口
EN

Stack Overflow用户
提问于 2017-05-03 22:46:56
回答 2查看 5K关注 0票数 1

我在我的项目中使用ReactJS,我想通过使用window.location.href来访问我当前的网址。当我使用window.location.href时,我得到一个错误,告诉我窗口没有定义。

代码语言:javascript
复制
// --- 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>
    );
};
EN

回答 2

Stack Overflow用户

发布于 2017-05-03 23:04:04

位置在道具中,因为窗口没有在React中定义。

只需执行this.props.location.pathname而不是window.location.href

更多的信息,如果你记录道具。

票数 0
EN

Stack Overflow用户

发布于 2018-02-27 04:44:16

安装这个库npm install --save-dev --save-exact jsdom jsdom-global,然后将它导入到您的组件顶部import 'jsdom-global/register';希望它能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43763367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档