react通过js实现跳转
使用 window.location 进行跳转
通过直接修改 window.location.href 或调用 window.location 的方法实现页面跳转。这种方式会触发页面刷新,适用于非 React Router 管理的场景。

// 直接修改 href
window.location.href = "https://example.com";
// 使用 assign(可回退)
window.location.assign("https://example.com");
// 使用 replace(不可回退)
window.location.replace("https://example.com");
使用 useNavigate(React Router v6)
在函数组件中,通过 React Router 的 useNavigate 钩子实现编程式导航,无需刷新页面。

import { useNavigate } from "react-router-dom";
function MyComponent() {
const navigate = useNavigate();
// 跳转到指定路径
const handleClick = () => {
navigate("/target-path");
};
// 带状态跳转
const navigateWithState = () => {
navigate("/target-path", { state: { id: 1 } });
};
return <button onClick={handleClick}>跳转</button>;
}
使用 history.push(React Router v5)
在类组件或旧版 React Router 中,通过 history 对象实现跳转。
import { withRouter } from "react-router-dom";
class MyComponent extends React.Component {
handleClick = () => {
this.props.history.push("/target-path");
};
render() {
return <button onClick={this.handleClick}>跳转</button>;
}
}
export default withRouter(MyComponent);
使用 <Navigate> 组件
通过条件渲染 <Navigate> 组件实现跳转,适用于需要根据状态(如登录验证)自动重定向的场景。
import { Navigate } from "react-router-dom";
function ProtectedRoute({ isAuthenticated }) {
return isAuthenticated ? <Dashboard /> : <Navigate to="/login" />;
}
注意事项
- 路由兼容性:
useNavigate仅适用于 React Router v6,v5 需使用history.push。 - 状态传递:通过
navigate或history.push的第二个参数可传递状态(如{ state: { data } })。 - 外部链接:跳转到外部域名时需使用
window.location,React Router 仅处理应用内路由。






