From d10ddb7d77dcd6634bfd0193201f6b1456e76828 Mon Sep 17 00:00:00 2001 From: Yiming Li Date: Fri, 13 Mar 2026 20:34:46 +0800 Subject: [PATCH] fix: avoid crash when spread undefined ref (#2333) ## Description Fixed a potential crash in `@lynx-js/react` when spreading props that include an undefined `ref`. This occurs because `applyRef` was being called even when the `ref` value was null or undefined in a spread object. Added a regression test in `packages/react/testing-library`. ## Checklist - [x] Tests updated (or not required). - [ ] Documentation updated (or not required). - [x] Changeset added, and when a BREAKING CHANGE occurs, it needs to be clearly marked (or not required). ## Summary by CodeRabbit * **Bug Fixes** * Fixed a crash that occurred when spreading properties containing undefined refs onto React components, improving application stability and reliability. --- .changeset/fix-spread-undefined-ref.md | 5 +++++ .../react/runtime/src/backgroundSnapshot.ts | 2 +- .../src/__tests__/ref.test.jsx | 22 +++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 .changeset/fix-spread-undefined-ref.md diff --git a/.changeset/fix-spread-undefined-ref.md b/.changeset/fix-spread-undefined-ref.md new file mode 100644 index 0000000000..0586d6bf78 --- /dev/null +++ b/.changeset/fix-spread-undefined-ref.md @@ -0,0 +1,5 @@ +--- +"@lynx-js/react": patch +--- + +fix: avoid crash when spread undefined ref diff --git a/packages/react/runtime/src/backgroundSnapshot.ts b/packages/react/runtime/src/backgroundSnapshot.ts index bf134d5915..0fe2675373 100644 --- a/packages/react/runtime/src/backgroundSnapshot.ts +++ b/packages/react/runtime/src/backgroundSnapshot.ts @@ -198,7 +198,7 @@ export class BackgroundSnapshotInstance { v.__snapshot_def.refAndSpreadIndexes?.forEach((i) => { const value = v.__values![i] as unknown; if (value && (typeof value === 'object' || typeof value === 'function')) { - if ('__spread' in value && 'ref' in value) { + if ('__spread' in value && 'ref' in value && value.ref) { applyRef(value.ref as Ref, null); } else if ('__ref' in value) { applyRef(value as Ref, null); diff --git a/packages/react/testing-library/src/__tests__/ref.test.jsx b/packages/react/testing-library/src/__tests__/ref.test.jsx index 51664bf58a..d1ca395752 100644 --- a/packages/react/testing-library/src/__tests__/ref.test.jsx +++ b/packages/react/testing-library/src/__tests__/ref.test.jsx @@ -460,4 +460,26 @@ describe('element ref', () => { expect(lynx.getNativeApp().callLepusMethod).toBeCalledTimes(2); vi.resetAllMocks(); }); + + it('spread undefined ref should work', () => { + let setProps, setShowChild; + const Child = () => { + const [props, _setProps] = useState({ ref: undefined }); + setProps = _setProps; + + return ; + }; + const App = () => { + let [showChild, _setShowChild] = useState(true); + setShowChild = _setShowChild; + + return showChild && ; + }; + + render(); + + act(() => { + setShowChild(false); + }); + }); });