2017-05-03 8 views
1

Ich verwende ReactJS in meinem Projekt und möchte auf meine aktuelle URL zugreifen, indem ich window.location.href verwende. Wenn ich window.location.href verwende, bekomme ich eine Fehlermeldung, dass das Fenster nicht definiert ist.Fenster ist nicht definiert

// --- 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

Überprüfen Sie diese http:// Stackoverflow.com/questions/35374257/error-window-not-defined-in-node-js scheint wie ein ähnliches Problem – Shota

Antwort

0

Die Position ist in den Requisiten, da Fenster in React nicht definiert ist.

Tun Sie einfach this.props.location.pathname anstelle von window.location.href.

Weitere Informationen, wenn Sie die Requisiten anmelden.

+0

TypeError: Kann nicht lesen Eigenschaft 'Requisiten' von undefined bei SampleApp (/Users/scrpatlolla/Desktop/Test/react-amp-template/examples/build/demo.js:41:24) unter/Benutzer/scrpatlolla/Desktop/Test/react-amp-template/node_modules/read-dom/lib/ReactCompositeComponent.js: 306: 16 bei measureLifeCyclePerf (/Users/scrpatlolla/Desktop/Test/react-amp-template/node_modules/react-dom/lib/ReactCompositeComponent.js:75:12) –

+0

Bitte beachten Sie den Fehler. wenn ich this.props.location.pathname verwende. –

+0

Bitte beachten Sie die vollständige Datei https://github.com/scrpatlolla/react-amp-template/blob/master/examples/src/demo.js –

0

Installieren Sie diese Bibliothek npm install --save-dev --save-exact jsdom jsdom-global importieren es dann an der Spitze Ihrer Komponente import 'jsdom-global/register'; Hoffe, es hilft.

Verwandte Themen