/**
 * 配合bundle-loader动态渲染组件
 * User: bjyangxiuwu
 * Date: 2017/07/05
 * Time: 10:09
 */
import PropTypes from 'prop-types';
import { Component } from 'react';

class Bundle extends Component {

  componentWillMount() {
    this.load(this.props)
  }

  componentWillReceiveProps(nextProps) {
    const { load } = this.props;
    if (nextProps.load !== load) {
      this.load(nextProps)
    }
  }

  load = (props) => {
    this.setState({
      mod: null
    });

    props.load((mod) => {
      this.setState({
        mod: mod.default ? mod.default : mod
      })
    })
  };

  render() {
    const { mod } = this.state;
    const { children } = this.props;
    return mod ? children(mod) : null;
  }
}

Bundle.propTypes = {
  load: PropTypes.func.isRequired,
  children: PropTypes.func.isRequired
};

export default Bundle;
