Webpack导入代码拆分呈现<未定义>

时间:2019-01-17 22:44:19

标签: javascript reactjs webpack preact

我正在尝试进行基于组件的代码拆分。 Webpack3。

    loadDecisions = async () => {
    if (!this.TmplDecisions) {
      this.TmplDecisions = await import(
        /* webpackChunkName: "chunk-templates-decisions" */ 'src/components/decisions'
      );
    }

    return this.TmplDecisions;
  }

  renderDecisions () {
    if (this.TmplDecisions && this.TmplDecisions.default) {
      return <this.TmplDecisions.default 
        {...this.props} 
        logOpenEvent={this.logTagOpenEvent}
      />;
    } else return null;
  };

该组件在开发工具调试器中显示正常,但将其呈现为<undefined></undefined>

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

您的路径名应以./开头,以便动态导入相关模块。

例如:/* webpackChunkName: "chunk-templates-decisions" */ './src/components/decisions.js'(此处请注意./,否则webpack将src视为npm模块)。

答案 1 :(得分:0)

来自React docs

  

您不能将通用表达式用作React元素类型。如果您确实想使用通用表达式来表示元素的类型,只需先将其分配给大写的变量即可。

因此,请先尝试将类型分配给大写变量。

还要在状态中添加TmplDecisions(或使用标志,例如tmplDecisionsLoaded),以便在加载TmplDecisions之后重新渲染React。

  loadDecisions = async () => {
    if (!this.state.TmplDecisions) {
      const TmplDecisions = await import(
        /* webpackChunkName: "chunk-templates-decisions" */ 'src/components/decisions'
      );

      this.setState({ TmplDecisions });
      return TmplDecisions;
    } else {
      return this.state.TmplDecisions;
    } 
  }

  renderDecisions () {
    if (this.state.TmplDecisions && this.state.TmplDecisions.default) {
      const MyComponent = this.state.TmplDecisions.default;
      return <MyComponent
        {...this.props} 
        logOpenEvent={this.logTagOpenEvent}
      />;
    } else return null;
  };

答案 2 :(得分:0)

您确定您一开始就没有将诺言传递给JSX吗? 那会让你不确定。

componentDidMount() {
  const TmplDecisions = this.TmplDecisions && this.TmplDecisions.default;
  if (TmplDecisions instanceof Promise) {
    TmplDecisions.then((RealTmplDecisions) => this.setState({ TmplDecisions: RealTmplDecisions}));
    return;
  }
  if (TmplDecisions instanceof Function) {
    this.setState({
      TmplDecisions
    });
    return;
  }
}

// On shouldComponentUpdate you need to check 
// if state.TmplDecisions !== undefined 
// among whatever else you are doing there

renderDecisions () {
  if (this.state.TmplDecisions) {
    return <this.state.TmplDecisions 
      {...this.props} 
      logOpenEvent={this.logTagOpenEvent}
    />;
  } else return null;
};