重复的browserHistory react-router

时间:2017-01-12 04:32:24

标签: reactjs react-router browser-history

我遇到以下代码问题: 这个代码的作用是当我打开或关闭时更改路径,它工作正常,但问题是每次更改它会使浏览器加倍,并导致网页被阻止

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>
    );
  }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

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

您应该使事件函数非匿名,并为路由添加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} />