-
Notifications
You must be signed in to change notification settings - Fork 2.5k
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
4 changed files
with
59 additions
and
51 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import { cloneEnumerableProperty } from '@alilc/lowcode-utils'; | ||
import adapter from '../adapter'; | ||
|
||
/** | ||
* 为什么要用 cache, | ||
* 因为 __getHOCWrappedComponent 会返回一个新的组件, | ||
* 如果不缓存,会导致组件每次渲染都是一次新的 mount | ||
*/ | ||
const componentCache = new Map(); | ||
|
||
export function errorBoundaryWrapper(Comp: any, { schema, baseRenderer }) { | ||
const { createElement, Component, forwardRef } = adapter.getRuntime(); | ||
const { engine } = baseRenderer.context; | ||
const componentCacheId = schema.id; | ||
|
||
if (componentCache.has(componentCacheId)) { | ||
return componentCache.get(componentCacheId); | ||
} | ||
|
||
class Wrapper extends Component { | ||
state = { error: null }; | ||
componentError = false; | ||
componentDidCatch(error: Error) { | ||
this.componentError = true; | ||
this.setState({ error }); | ||
} | ||
|
||
render() { | ||
if (this.componentError) { | ||
this.componentError = false; | ||
return engine.createElement(engine.getFaultComponent(), { | ||
...this.props, | ||
error: this.state.error, | ||
componentName: schema.componentName, | ||
}); | ||
} | ||
return createElement(Comp, { | ||
...this.props, | ||
ref: this.props.forwardRef, | ||
}); | ||
} | ||
} | ||
|
||
(Wrapper as any).displayName = Comp.displayName; | ||
|
||
let ErrorBoundary = cloneEnumerableProperty( | ||
forwardRef((props: any, ref: any) => { | ||
return createElement(Wrapper, { ...props, forwardRef: ref }); | ||
}), | ||
Comp, | ||
); | ||
|
||
componentCache.set(componentCacheId, ErrorBoundary); | ||
|
||
return ErrorBoundary; | ||
} |
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