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