温馨提示×

react路由怎么重定向到单页

小亿
177
2024-02-01 11:35:32
栏目: 编程语言

在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('/')方法,就可以将页面重定向到/

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

0