Last active
October 23, 2017 16:36
-
-
Save iinsta/aa444537ebc6921713db70f3435b602f to your computer and use it in GitHub Desktop.
react async load componet demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* opts = { | |
* load: () => import('./DemoComponent'), error: function(props) { return <div onClick={props.reload}>Load error</div>} | |
* } | |
* | |
*/ | |
import React, {BasicComponent} from 'ReactBasicComponent' | |
function asyncLoad(opts) { | |
const {load, error as ErrorComponent, Loading} = opts; | |
return class AsyncLoad extends BasicComponent { | |
state = { | |
component: null, | |
status: 'loading', | |
} | |
didMount() { | |
this.load() | |
} | |
load => { | |
this.state.status === 'error' && this.updateState({ | |
status: 'loading', | |
}) | |
load().then(res => { | |
this.updateState({ | |
status: 'ok', | |
component: res | |
}) | |
}).catch(e => { | |
this.updateState({ | |
status: 'e' | |
}) | |
}) | |
} | |
render() { | |
const {component, status} = this.state | |
let TmpComponent = null | |
switch(status) { | |
case null: | |
break | |
case 'loading': | |
TmpComponent = <Loading /> | |
break | |
case 'error': | |
TmpComponent = <ErrorComponent reload={this.load}/> | |
break | |
default: | |
TmpComponent = <component /> | |
} | |
return TmpComponent | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
export default React | |
export class BasicComponent extends React.Component { | |
componentWillUnmount() { | |
this.willUnmount && this.willUnmount() | |
this.__unmount = true | |
} | |
componentDidMount() { | |
this.didMount && this.didMount() | |
} | |
updateState(){ | |
this.__unmount && this.setState(...arguments) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment