为什么这个反应组件,用System.import导入,而不是渲染?

时间:2017-02-06 12:29:40

标签: javascript reactjs webpack webpack-2 es6-modules

我正在尝试使用webpack 2实现动态代码拆分并做出反应。为了测试,我创建了一个异步提取代码的组件:

import React, { Component } from 'react'

export class Async extends Component {
  constructor(props) {
    super(props)
    this.state = { component: <div>Loading</div> }
  }

  componentDidMount() {
    System.import('../../about')
      .then(component => this.setState({ component: component.About }))
      .catch(error => this.setState({ component: <div>{error.message}</div> }))
  }

  render() {
    return this.state.component
  }
}

但是,当我挂载它时,它会返回以下错误:

Async.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Async的渲染功能中放置console.log(this.state.component)会产生以下结果:

enter image description here

那么这里出了什么问题?看起来我得到了有效的反应组件,为什么它会抛出错误?

2 个答案:

答案 0 :(得分:0)

我认为你必须在this.state.component{}内包裹<div>以及错误是什么

您需要从组件

中创建一个元素

class Async extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      component: React.createElement('div', {}, "loading")
    }
  }
  render() {
    return (
      this.state.component
    )
  }

}

ReactDOM.render(<Async/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="app"></div>

class Async extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      component: React.createElement('div', {}, "loading")
    }
  }
componentDidMount() {
    System.import('../../about')
      .then(component => this.setState({ component: React.createElement(component.About) }))
      .catch(error => this.setState({ component: React.createElement('div', {}, error.message) }))
  }
  render() {
    return (
      this.state.component
    )
  }

}

答案 1 :(得分:0)

当你实际上应该从那个类返回一个从创建的元素时,你将返回组件类。他们不是一回事!

// Replace this:

render() {
    return this.state.component
}

// With this:

render() {
    return <this.state.component />
}

// Or this:

render() {
   return React.createElement(this.state.component)
}