1 |
3a515b92
|
cagy
|
import React from "react";
|
2 |
|
|
import PropTypes from "prop-types";
|
3 |
|
|
import invariant from "tiny-invariant";
|
4 |
|
|
|
5 |
|
|
import Lifecycle from "./Lifecycle";
|
6 |
|
|
import RouterContext from "./RouterContext";
|
7 |
|
|
|
8 |
|
|
/**
|
9 |
|
|
* The public API for prompting the user before navigating away from a screen.
|
10 |
|
|
*/
|
11 |
|
|
function Prompt({ message, when = true }) {
|
12 |
|
|
return (
|
13 |
|
|
<RouterContext.Consumer>
|
14 |
|
|
{context => {
|
15 |
|
|
invariant(context, "You should not use <Prompt> outside a <Router>");
|
16 |
|
|
|
17 |
|
|
if (!when || context.staticContext) return null;
|
18 |
|
|
|
19 |
|
|
const method = context.history.block;
|
20 |
|
|
|
21 |
|
|
return (
|
22 |
|
|
<Lifecycle
|
23 |
|
|
onMount={self => {
|
24 |
|
|
self.release = method(message);
|
25 |
|
|
}}
|
26 |
|
|
onUpdate={(self, prevProps) => {
|
27 |
|
|
if (prevProps.message !== message) {
|
28 |
|
|
self.release();
|
29 |
|
|
self.release = method(message);
|
30 |
|
|
}
|
31 |
|
|
}}
|
32 |
|
|
onUnmount={self => {
|
33 |
|
|
self.release();
|
34 |
|
|
}}
|
35 |
|
|
message={message}
|
36 |
|
|
/>
|
37 |
|
|
);
|
38 |
|
|
}}
|
39 |
|
|
</RouterContext.Consumer>
|
40 |
|
|
);
|
41 |
|
|
}
|
42 |
|
|
|
43 |
|
|
if (__DEV__) {
|
44 |
|
|
const messageType = PropTypes.oneOfType([PropTypes.func, PropTypes.string]);
|
45 |
|
|
|
46 |
|
|
Prompt.propTypes = {
|
47 |
|
|
when: PropTypes.bool,
|
48 |
|
|
message: messageType.isRequired
|
49 |
|
|
};
|
50 |
|
|
}
|
51 |
|
|
|
52 |
|
|
export default Prompt;
|