<Navigate>
declare function Navigate(props: NavigateProps): null;
interface NavigateProps {
to: To;
replace?: boolean;
state?: any;
relative?: RelativeRoutingType;
}
<Navigate>
元素在渲染时会更改当前位置。它是 useNavigate
的组件包装器,并接受与 props 相同的所有参数。
useNavigate
hook 版本使得在 React.Component
子类中更容易使用此功能,因为在子类中无法使用 hook。
import * as React from "react";
import { Navigate } from "react-router-dom";
class LoginForm extends React.Component {
state = { user: null, error: null };
async handleSubmit(event) {
event.preventDefault();
try {
let user = await login(event.target);
this.setState({ user });
} catch (error) {
this.setState({ error });
}
}
render() {
let { user, error } = this.state;
return (
<div>
{error && <p>{error.message}</p>}
{user && (
<Navigate to="/dashboard" replace={true} />
)}
<form
onSubmit={(event) => this.handleSubmit(event)}
>
<input type="text" name="username" />
<input type="password" name="password" />
</form>
</div>
);
}
}