Commit 8b945342 authored by Naoyuki Kanezawa's avatar Naoyuki Kanezawa Committed by Guillermo Rauch

Wrap render method created using class properties (2) (#856)

* wrap render method created using class properties

* use Boolean instead of double not-operator

* patch-react: move a comment
parent 4b257483
...@@ -17,8 +17,23 @@ export default (handleError = () => {}) => { ...@@ -17,8 +17,23 @@ export default (handleError = () => {}) => {
React.createElement = function (Component, ...rest) { React.createElement = function (Component, ...rest) {
if (typeof Component === 'function') { if (typeof Component === 'function') {
const { prototype } = Component const { prototype } = Component
if (prototype && prototype.render) {
prototype.render = wrapRender(prototype.render) // assumes it's a class component if render method exists.
const isClassComponent = Boolean(prototype && prototype.render) ||
// subclass of React.Component or PureComponent with no render method.
// There's no render method in prototype
// when it's created with class-properties.
prototype instanceof React.Component ||
prototype instanceof React.PureComponent
if (isClassComponent) {
if (prototype.render) {
prototype.render = wrapRender(prototype.render)
}
// wrap the render method in runtime when the component initialized
// for class-properties.
Component = wrap(Component, withWrapOwnRender)
} else { } else {
// stateless component // stateless component
Component = wrapRender(Component) Component = wrapRender(Component)
...@@ -39,24 +54,42 @@ export default (handleError = () => {}) => { ...@@ -39,24 +54,42 @@ export default (handleError = () => {}) => {
} }
function wrapRender (render) { function wrapRender (render) {
if (render.__wrapped) { return wrap(render, withHandleError)
return render.__wrapped }
}
const _render = function (...args) { function withHandleError (fn, ...args) {
try { try {
return render.apply(this, args) return fn.apply(this, args)
} catch (err) { } catch (err) {
handleError(err) handleError(err)
return null return null
}
} }
}
// copy all properties function withWrapOwnRender (fn, ...args) {
Object.assign(_render, render) const result = fn.apply(this, args)
if (this.render && this.hasOwnProperty('render')) {
this.render = wrapRender(this.render)
}
return result
}
}
render.__wrapped = _render.__wrapped = _render function wrap (fn, around) {
if (fn.__wrapped) {
return fn.__wrapped
}
return _render const _fn = function (...args) {
return around.call(this, fn, ...args)
} }
// copy all properties
Object.assign(_fn, fn)
_fn.prototype = fn.prototype
_fn.__wrapped = fn.__wrapped = _fn
return _fn
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment