重复浏览器历史反应路由器

duplicate browserHistory react-router

我对以下代码有疑问: 这段代码的作用是在向上或向下键入时更改路径,它工作正常,但问题是每次更改它都会使浏览器加倍,并导致网页被阻止

function homeChange(e){

  $(window).keydown(function(event) { 
    if(event.which==40){
      browserHistory.push('/aplicaciones_moviles');
      console.log(browserHistory)
    }
  });
}
function appServiceChange(){
  $(window).keydown(function(event) { 
    if(event.which==40){
      console.log(browserHistory)
      browserHistory.push('/software_medida');
    }else if(event.which==38){
      browserHistory.push('/aplicaciones_moviles');
      console.log(browserHistory)
    }
  });

}
function softwareServiceChange(){
  $(window).keydown(function(event) { 
    if(event.which==40){
      console.log(event)
      browserHistory.push('/portafolio');
    }else if(event.which==38){
      browserHistory.push('/aplicaciones_moviles');
    }
  });
}

function portafolioChange(){
  $(window).keydown(function(event) { 
    if(event.which==40){
      console.log(event)
      browserHistory.push('/');
    }else if(event.which==38){
      browserHistory.push('/software_medida');
    }
  });
}

export default class Routes extends Component {
  render() {
    return (
      <Router history={browserHistory} >
        <Route path='/' component={HomeLayout} onEnter={homeChange} >
          <IndexRoute component={HomeComponent} />
        </Route>
        <Route path='aplicaciones_moviles' component={AppServiceLayout} onEnter={appServiceChange} >
          <IndexRoute  />
        </Route>
        <Route path='software_medida' component={softwareServiceLayout} onEnter={softwareServiceChange}>
          <IndexRoute  />
        </Route>        
        <Route path='portafolio' component={portafolioLayout} onEnter={portafolioChange}>
          <IndexRoute  />
        </Route>
        <Route path='*' component={HomeLayout}>
          <IndexRoute component={NotFoundComponent} />
        </Route>
      </Router>
    );
  }
}

您似乎在路由进入时添加事件侦听器,但在路由离开时它们并未被删除。这意味着您有多个侦听器对 keydown 事件作出反应。

您应该使事件函数 non-anonymous 并向路由添加一个 onLeave 挂钩。

function portafolioEvent(event) { 
  if(event.which==40){
    console.log(event)
    browserHistory.push('/');
  } else if(event.which==38){
    browserHistory.push('/software_medida');
  }
}

function addPortafolioListener() {
  $(window).on('keydown', portafolioEvent);
}

function removePortafolioListener() {
  $(window).off('keydown', portafolioEvent);
}

<Route
  path='portafolio'
  component={portafolioLayout}
  onEnter={addPortafolioListener}
  onLeave={removePortafolioListener} />