[英]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.