-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
364 additions
and
4 deletions.
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import { Component } from './component'; | ||
import { createElement } from './create-element'; | ||
|
||
// TODO: react warns in dev mode about defaultProps and propTypes not being supported on lazy | ||
// loaded components | ||
|
||
export const sym = '_s'; | ||
|
||
export const Suspense2 = 'suspense'; | ||
|
||
export class Suspense extends Component { | ||
constructor(props) { | ||
// TODO: should we add propTypes in DEV mode? | ||
super(props); | ||
|
||
// mark this component as a handler of suspension (thrown Promises) | ||
this[sym] = sym; | ||
|
||
this.state = { | ||
l: false | ||
}; | ||
} | ||
|
||
componentDidCatch(e) { | ||
if (e && typeof e.then === 'function') { | ||
this.setState({ l: true }); | ||
const cb = () => { this.setState({ l: false }); }; | ||
|
||
// Suspense ignores errors thrown in Promises as this should be handled by user land code | ||
e.then(cb, cb); | ||
} | ||
else { | ||
throw e; | ||
} | ||
} | ||
|
||
render() { | ||
return this.state.l ? this.props.fallback : this.props.children; | ||
} | ||
} | ||
|
||
export function lazy(loader) { | ||
let prom; | ||
let component; | ||
let error; | ||
return function Lazy(props) { | ||
if (!prom) { | ||
prom = loader(); | ||
prom.then( | ||
({ default: c }) => { component = c; }, | ||
e => error = e, | ||
); | ||
} | ||
|
||
if (error) { | ||
throw error; | ||
} | ||
|
||
if (!component) { | ||
throw prom; | ||
} | ||
|
||
return createElement(component, props); | ||
}; | ||
} |
Oops, something went wrong.