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

228
Visualizações
Override the back button route with react router replace method on componentWillUnmount

I have a component, which is A and on success of some form filling, i route the user to the B component. Now when the user clicks on back button of browser, instead of going back to A component, i re route him to the Home Page

App.js

<Route exact path="/">
   <Root />
 </Route>
 <Route path="/home">
   <Home />
 </Route>
 <Route path="/a">
   <A />
 </Route>
 <Route path="/b">
   <B />
 </Route>

A.js

 componentDidMount() {
    console.log("api call");
  }

  handleSubmit = () => {
    // api success
    this.props.history.push({
      pathname: "/b",
      search: "?viewType=success"
    });
  };

B.js

backListener() {
    if (this.props.history.action === "POP") {
      let viewType = new URLSearchParams(this.props.location?.search)?.get(
        "viewType"
      );
      if (viewType === "success") {
        return this.props.history.replace("/home");
      }
      return this.props.history.replace("/");
    }
  }

  componentDidMount() {
    window.addEventListener("popstate", this.backListener);
  }

  componentWillUnmount() {
    this.backListener();
    window.removeEventListener("popstate", this.backListener);
  }

Even though i am pushing the route to /home, but i can see the A.js log of api calling

I don't want to render the A.js from B when the browser back button is clicked.

What am i doing wrong here

Sandbox

Steps:

  1. Click on Go To A
  2. Click on Submit
  3. Click on back button of sandbox
  4. In the console its showing api call (2 times)

How could i override the back button component load when i am pushing the state on componentWillUnmount ?

about 4 years ago · Juan Pablo Isaza
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