Prompt.js 1.3 KB

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