如何使用 React Router 在 React 中重定向而不闪烁?

Ole*_*nov 7 javascript reactjs react-router

我正在使用 React Router 构建一个 SPA,并遇到了这个概念问题。

这是我的应用程序组件,它有一个 React Router。

class App extends Component {
  render(){
    return(
      <div className="appwrap">
        <Jumbotron></Jumbotron>
        <Navbar></Navbar>
        <Router>
          <Route exact path="/" component={Display}></Route>
          <Route exact path="/saved" component={Saved}></Route>
        </Router>
        <Footer></Footer>
      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的导航栏组件中,有几个重定向到 href 的简单函数,这显然会导致页面“闪烁”和刷新。这就是我想要摆脱的(闪烁)。我的导航栏组件就在这里。

class Navbar extends Component {
  redirectToSearch = () => {
    window.location.href = '/'; 
  }
  redirectToSaved = () => {
    window.location.href = '/saved'; 
  }
  render(){
    return (
      <div className="navbar">
          <div className="navbaropt" onClick={this.redirectToSearch.bind(this)}>search</div>
          <div className="navbaropt" onClick={this.redirectToSaved.bind(this)}>saved</div>
      </div>
    );}
}
Run Code Online (Sandbox Code Playgroud)

Avi*_*ish 7

对于 React Router 的页内导航,您必须使用该Link元素。

  <div className="navbar">
      <Link to="/">search</Link>
      <Link to="/saved">saved</Link>
  </div>
Run Code Online (Sandbox Code Playgroud)

在这里阅读所有相关内容

  • 我什至无法理解这里发生了什么。您原来的问题中没有任何内容远程表明您不想使用链接标签。 (2认同)
  • 此外,您可以通过在构造函数中仅绑定一次而不是每次渲染来节省一些周期。但你甚至不需要绑定,因为你使用的是箭头函数 (2认同)

Tii*_*ane 4

我遇到了同样的问题,并在以下帖子中找到了解决方案:使用 React router 以编程方式导航

window.location.href用。。。来代替this.props.navigation.push

将您的功能更新为以下内容

redirectToSearch = () => this.props.navigation.push('/');

redirectToSaved = () => this.props.navigation.push('/saved');
Run Code Online (Sandbox Code Playgroud)