From 4d0c3f447108c6234747abbe44508e923b9abffc Mon Sep 17 00:00:00 2001 From: Clarence Pan Date: Fri, 20 Aug 2021 10:26:30 +0800 Subject: [PATCH] fix(rax): add lacked input argument of getDerivedStateFromError (fix #2211) (#2212) * fix(rax): add lacked input argument of getDerivedStateFromError https://github.com/alibaba/rax/issues/2211 * test(rax): add test for getDerivedStateFromError first argument of getDerivedStateFromError should be the thrown error --- packages/rax/src/vdom/__tests__/composite.js | 40 ++++++++++++++++++++ packages/rax/src/vdom/performInSandbox.js | 2 +- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/packages/rax/src/vdom/__tests__/composite.js b/packages/rax/src/vdom/__tests__/composite.js index c1db46878..a29fe42e1 100644 --- a/packages/rax/src/vdom/__tests__/composite.js +++ b/packages/rax/src/vdom/__tests__/composite.js @@ -762,6 +762,46 @@ describe('CompositeComponent', function() { expect(container.childNodes[0].childNodes[0].data).toBe('Something went wrong.'); }); + it('should catch the exact error with getDerivedStateFromError.', () => { + let caughtError; + let exampleError = new Error('Example error message'); + let container = createNodeElement('div'); + + class ErrorBoundary extends Component { + constructor(props) { + super(props); + this.state = { hasError: false, error: null }; + } + + static getDerivedStateFromError(error) { + caughtError = error; + return { hasError: true, error }; + } + + render() { + if (this.state.hasError) { + return

{this.state.error.message}

; + } + + return this.props.children; + } + } + + function BrokenRender(props) { + throw exampleError; + } + + render( + + + , container); + + jest.runAllTimers(); + + expect(caughtError).toBe(exampleError); + expect(container.childNodes[0].childNodes[0].data).toBe('Example error message'); + }); + it('should render correct when prevRenderedComponent did not generate nodes', () => { let container = createNodeElement('div'); class Frag extends Component { diff --git a/packages/rax/src/vdom/performInSandbox.js b/packages/rax/src/vdom/performInSandbox.js index fd15cb3af..fda3b71eb 100644 --- a/packages/rax/src/vdom/performInSandbox.js +++ b/packages/rax/src/vdom/performInSandbox.js @@ -39,7 +39,7 @@ export function handleError(instance, error) { // Update state to the next render to show the fallback UI. if (boundary.constructor && boundary.constructor.getDerivedStateFromError) { - const state = boundary.constructor.getDerivedStateFromError(); + const state = boundary.constructor.getDerivedStateFromError(error); boundary.setState(state); } }, boundaryInternal.__parentInstance);