Linux 拨号vps windows公众号手机端

react路由怎么重定向到单页

lewis 9年前 (2017-02-09) 阅读数 13 #程序编程
文章标签 React

在React中,可以通过使用<Redirect>组件或者编程式导航来实现路由重定向到单页。

  1. 使用<Redirect>组件:
import { Redirect } from 'react-router-dom';

function App() {
  return (
    <div>
      {/* 定义路由 */}
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        {/* 定义重定向 */}
        <Redirect to="/" />
      </Switch>
    </div>
  );
}

在上述示例中,如果用户访问除了//about之外的路径,将会被重定向到/

  1. 使用编程式导航:
import { useHistory } from 'react-router-dom';

function App() {
  const history = useHistory();

  // 在需要重定向的地方调用以下代码
  history.push('/');

  return (
    <div>
      {/* 定义路由 */}
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </div>
  );
}

在上述示例中,通过调用history.push('/')方法,就可以将页面重定向到/

无论采用哪种方式,重定向到单页都是通过定义路由并在特定条件下触发重定向来实现的。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门