溫馨提示×

react路由怎么重定向到單頁

小億
198
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女