Check if devtools hook on/off methods are defined before using them in AppContainer (#39808)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/39808

I've been doing some tests where I disable React DevTools locally and this code has been crashing because React Fast Refresh defines the React DevTools hook if DevTools didn't ([pointer](https://github.com/facebook/react/blob/85c2b519b54269811002d26f4f711809ef68f123/packages/react-refresh/src/ReactFreshRuntime.js#L453-L475)), and it doesn't actually define the `on` and `off` methods, which makes this throw.

This changes `AppContainer` to check if the methods are defined before using them.

Changelog: [internal]

Reviewed By: hoxyq

Differential Revision: D49909258

fbshipit-source-id: 3b0c1f37601a1cbe38f80ca3a20ffe2348a21aaf
This commit is contained in:
Rubén Norte
2023-10-04 09:50:43 -07:00
committed by Facebook GitHub Bot
parent d9cc662212
commit e284bdc869
+10 -5
View File
@@ -94,10 +94,12 @@ class AppContainer extends React.Component<Props, State> {
this._reactDevToolsAgentListener = () =>
this.mountReactDevToolsOverlays();
reactDevToolsHook.on(
'react-devtools',
this._reactDevToolsAgentListener,
);
if (reactDevToolsHook.on != null) {
reactDevToolsHook.on(
'react-devtools',
this._reactDevToolsAgentListener,
);
}
}
}
}
@@ -108,7 +110,10 @@ class AppContainer extends React.Component<Props, State> {
this._subscription.remove();
}
if (reactDevToolsHook != null && this._reactDevToolsAgentListener != null) {
if (
reactDevToolsHook?.off != null &&
this._reactDevToolsAgentListener != null
) {
reactDevToolsHook.off('react-devtools', this._reactDevToolsAgentListener);
}
}