使用 React router v6,您可以使用 useEffect 创建重定向:
import React, { useEffect } from 'react';
import {
BrowserRouter, Route, Routes, useNavigate,
} from 'react-router-dom';
const App = () => (
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/home" element={<Home />} />
</Routes>
</BrowserRouter>
</div>
);
const Main = () => {
const navigate = useNavigate();
useEffect(() => {
let didCancel = false;
const goToHomePage = () => navigate('/home');
if (!didCancel) { goToHomePage(); }
return () => { didCancel = true; };
}, [navigate]);
return (
<div>
<h1>Welcome Main!</h1>
</div>
);
};
const Home = () => (
<div>
<h1>Welcome Home!</h1>
</div>
);
export default App;
如果要创建到另一个组件的替代重定向,可以按如下方式进行:
import React, { useEffect } from 'react';
import {
BrowserRouter, Route, Routes, useNavigate,
} from 'react-router-dom';
const App = () => (
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/home" element={<Home />} />
<Route path="/other" element={<Other />} />
</Routes>
</BrowserRouter>
</div>
);
const Main = () => {
const navigate = useNavigate();
useEffect(() => {
let didCancel = false;
const goToHomePage = () => navigate('/home');
const goToOtherPage = () => navigate('/other');
if (!didCancel) { goToHomePage(); } else { goToOtherPage(); }
return () => { didCancel = true; };
}, [navigate]);
return (
<div>
<h1>Welcome Main!</h1>
</div>
);
};
const Home = () => (
<div>
<h1>Welcome Home!</h1>
</div>
);
const Other = () => (
<div>
<h1>Welcome Other!</h1>
</div>
);
export default App;
在更改旧语法的 React 路由器 5 中,它也应该可以工作。然而,在 React 路由器 6 中我没有找到 Redirect 所以上面的重定向更有用。