在React中,可以通过使用<Redirect>组件或者编程式导航来实现路由重定向到单页。
<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之外的路径,将会被重定向到/。
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('/')方法,就可以将页面重定向到/。
无论采用哪种方式,重定向到单页都是通过定义路由并在特定条件下触发重定向来实现的。


