2017-02-06 200 views
0

我正在嘗試使用webpack 2實現動態代碼拆分並作出反應。爲了測試我創建了代碼異步牽引組件:爲什麼這反應組件,導入System.import,不渲染?

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的渲染功能,結果如下:

enter image description here

那麼什麼錯嗎?看起來好像我得到了有效的反應組件,那爲什麼它會拋出一個錯誤?

+0

應該從'react''導入React,{Component} from'react''不是'import {React,Component}嗎? – evolutionxbox

+0

@evolutionxbox不,React是'react'包的默認導出 – vsjn3290ckjnaoij2jikndckjb

回答

1

你正在返回組件類,當你應該實際上是返回從那個類創建的元素。他們不是一回事!

// Replace this: 

render() { 
    return this.state.component 
} 

// With this: 

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

// Or this: 

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

這不起作用,因爲this.state.component並不總是一個類。但是'.then(component => this.setState({component:React.createElement(component.About)}))'確實解決了它。謝謝! – vsjn3290ckjnaoij2jikndckjb

+0

@ismay:好點! –

0

我想你一定包裹內{}​​和<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 
    ) 
    } 

} 
的創建一個元素
+0

看看我的更新回答 –