美文网首页
react-router源码分析------Prompt

react-router源码分析------Prompt

作者: iqing2012 | 来源:发表于2018-06-07 16:36 被阅读12次
    import React from "react";
    import PropTypes from "prop-types";
    import invariant from "invariant";
    
    /**
     * The public API for prompting the user before navigating away
     * from a screen with a component.
      用于提示用户的公共API,然后用组件导航离开屏幕。
     */
    class Prompt extends React.Component {
      static propTypes = {
        when: PropTypes.bool,
        message: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired
      };
    
      static defaultProps = {
        when: true
      };
    
      static contextTypes = {
        router: PropTypes.shape({
          history: PropTypes.shape({
            block: PropTypes.func.isRequired
          }).isRequired
        }).isRequired
      };
    
      enable(message) {
        if (this.unblock) this.unblock();
    
        this.unblock = this.context.router.history.block(message);
      }
    
      disable() {
        if (this.unblock) {
          this.unblock();
          this.unblock = null;
        }
      }
    
      componentWillMount() {
        invariant(
          this.context.router,
          "You should not use <Prompt> outside a <Router>"
        );
    
        if (this.props.when) this.enable(this.props.message);
      }
    
      componentWillReceiveProps(nextProps) {
        if (nextProps.when) {
          if (!this.props.when || this.props.message !== nextProps.message)
            this.enable(nextProps.message);
        } else {
          this.disable();
        }
      }
    
      componentWillUnmount() {
        this.disable();
      }
    
      render() {
        return null;
      }
    }
    
    export default Prompt;
    

    相关文章

      网友评论

          本文标题:react-router源码分析------Prompt

          本文链接:https://www.haomeiwen.com/subject/scbgsftx.html