【问题标题】:Window is not defined窗口未定义
【发布时间】:2017-10-01 11:33:00
【问题描述】:

我在我的项目中使用 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>
    );
};

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

位置在 props 中,因为在 React 中没有定义 window。

只需使用this.props.location.pathname 而不是window.location.href

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

【讨论】:

  • TypeError: Cannot read property 'props' of undefined at SampleApp (/Users/scrpatlolla/Desktop/Test/react-amp-template/examples/build/demo.js:41:24) at /用户/scrpatlolla/Desktop/Test/react-amp-template/node_modules/react-dom/lib/ReactCompositeComponent.js:306:16 at measureLifeCyclePerf (/Users/scrpatlolla/Desktop/Test/react-amp-template/node_modules/react -dom/lib/ReactCompositeComponent.js:75:12)
  • 请查看错误。如果我使用 this.props.location.pathname.
  • 你有一个纯组件。传递给纯组件的第一个参数是 props。
  • 您必须像提取值一样提取位置:const SampleApp = ({ value, location }) = { ... }
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2019-06-03
    • 2021-01-15
    • 2019-10-12
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多