2017-05-03 100 views
1

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

入住這http://stackoverflow.com/questions/35374257/error-window-not-defined-in-node-js似乎是一個類似的問題 – Shota

回答

0

位置在道具中,因爲窗口沒有在React中定義。

只要做this.props.location.pathname而不是window.location.href

更多信息,如果你登錄道具。

+0

類型錯誤:無法在SampleApp讀的不確定 財產「道具」( /Users/scrpatlolla/Desktop/Test/react-amp-template/examples/build/demo.js:41:24) at/Users/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) –

+0

請參閱錯誤。如果我使用this.props.location.pathname。 –

+0

請參閱完整文件https://github.com/scrpatlolla/react-amp-template/blob/master/examples/src/demo.js –

0

安裝這個庫 npm install --save-dev --save-exact jsdom jsdom-global 然後在你的組件的頂部 import 'jsdom-global/register'; 希望它可以幫助導入。