🤖 Merge PR #46565 [react-router][v3] Fix router.setRouteLeaveHook signature by @MrOrz

* Fix setRouteLeaveHook signature

router.setRouteLeaveHook() should return a function that unbinds the listener.

@see [react-router v3 API](https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#setrouteleavehookroute-hook)
@see [react-router v3 Implementation: router object](https://github.com/ReactTraining/react-router/blob/v3/modules/RouterUtils.js#L4)
@see [react-router v3 lsitenBeforeLeavingRoute](https://github.com/ReactTraining/react-router/blob/v3/modules/createTransitionManager.js#L204-L206)

* Add setRouteLeaveHook return type test

* Fix lint for react-router-tests.tsx

Co-authored-by: Johnson Liang <johnson.liang@appier.com>
This commit is contained in:
Johnson Liang 2020-08-12 10:27:03 +08:00 committed by GitHub
parent 4672781367
commit 1dc4371d07
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 1 deletions

View File

@ -51,7 +51,7 @@ type LocationFunction = (location: LocationDescriptor) => void;
type GoFunction = (n: number) => void;
type NavigateFunction = () => void;
type ActiveFunction = (location: LocationDescriptor, indexOnly?: boolean) => boolean;
type LeaveHookFunction = (route: any, callback: RouteHook) => void;
type LeaveHookFunction = (route: any, callback: RouteHook) => () => void;
type CreatePartFunction<Part> = (pathOrLoc: LocationDescriptor, query?: any) => Part;
export interface InjectedRouter {

View File

@ -167,6 +167,21 @@ class User extends React.Component<UserProps> {
}
}
const CreateForm: React.FC<WithRouterProps> = ({ router }) => {
const [dirty] = React.useState<boolean>(false);
React.useEffect(() => {
const unbind = router.setRouteLeaveHook('/create', () => {
if (dirty) return 'Are you sure?';
});
return () => {
unbind();
};
}, [router, dirty]);
return <form></form>;
};
ReactDOM.render((
<Router history={hashHistory}>
<Route path="/" component={Master}>
@ -175,6 +190,7 @@ ReactDOM.render((
<Route path="user/:id" component={User} />
<Route path="*" component={NotFound} />
</Route>
<Route path="/create" component={CreateForm} />
</Router>
), document.body);