Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

71
Visualizações
eventListener for hashChange

I am trying to add an event listener for my page in ReactJS. I have added it to componentDidMount(). But the is only triggered for the initial page load.

How can I get it trigger whenever there is a change in the address bar.

componentDidMount:function(){

        window.addEventListener("hashchange", console.log('hashchange1'));
        $(window).bind("hashchange", console.log('$ - hashchange'));
        window.onhashchange =  console.log('hashchange3');      
        ReactDOM.findDOMNode(this).addEventListener('hashChange',console.log('ReactDOM - hashchange'));
    },

I've tried several different ways to get it to work, but they all work only on the first load. What am I doing wrong?

Thanks.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You're just executing the console.log in every case, and adding its return value as the listener. You need to pass a function as an event listener, for example:

window.addEventListener("hashchange", e => console.log('hashchange1', window.location.hash ));

https://jsfiddle.net/ku6okrp2/

EDIT to make it look more obvious using ES5:

window.addEventListener("hashchange", function(e){ 
  console.log('hashchange1', window.location.hash )
});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda