【问题标题】:Why does this react component, imported with System.import, not render?为什么这个用 System.import 导入的反应组件不渲染?
【发布时间】:2017-06-23 09:34:49
【问题描述】:

我正在尝试使用 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) 会产生以下结果:

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

【问题讨论】:

  • 应该import React, { Component } from 'react' 不是import { React, Component } from 'react'
  • @evolutionxbox 不,React 是“react”包的默认导出

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


【解决方案1】:

我认为您必须将 this.state.component 包装在 {}&lt;div&gt; 中,并且错误是关于什么的

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

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

}

【讨论】:

    【解决方案2】:

    您正在返回组件类,而实际上您应该返回从该类创建的元素。它们不是一回事!

    // Replace this:
    
    render() {
        return this.state.component
    }
    
    // With this:
    
    render() {
        return <this.state.component />
    }
    
    // Or this:
    
    render() {
       return React.createElement(this.state.component)
    }
    

    【讨论】:

    • 这不起作用,因为 this.state.component 并不总是一个类。但是.then(component =&gt; this.setState({ component: React.createElement(component.About) })) 确实解决了它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-10-11
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    相关资源
    最近更新 更多