繁体   English   中英

为什么此反应组件(使用System.import导入)不渲染?

[英]Why does this react component, imported with System.import, not render?

我正在尝试使用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.

将console.log(this.state.component)放入Async的render函数中会导致以下结果:

在此处输入图片说明

那么,这里出了什么问题? 看来我正在获得有效的React组件,那么为什么会引发错误?

我认为您必须在{}<div>包装this.state.component ,并且该错误是关于

您需要从组件中创建一个元素

 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
    )
  }

}

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

// Replace this:

render() {
    return this.state.component
}

// With this:

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

// Or this:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM