react-routerを使用して、どのように単一ページにリダイレクトするのか。

Reactでは、コンポーネントを使用するか、プログラムでナビゲーションを行うことで、ページをリダイレクトすることができます。

  1. リダイレクト
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(‘/’)メソッドを呼び出すことで、ページを/にリダイレクトすることができます。

どのような方法を採用しても、単一のページにリダイレクトすることは、ルートを定義し、特定の条件下でリダイレクトをトリガーすることで実現されます。

bannerAds