From 7b9bd8560e3ed9454bca2006a9b88e0bdab0bd0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20B=C3=BCchele?= Date: Mon, 22 Oct 2018 06:58:02 -0700 Subject: [PATCH] update PluginContainer to new React API Summary: React has a built in API for computing the state from props called `getDerivedStateFromProps`. So let's use this instead of our custom implementation. Reviewed By: jknoxville Differential Revision: D10484213 fbshipit-source-id: 4c434c5252dabfc2f6015cb6a50719b985c60446 --- src/PluginContainer.js | 75 +++++++++++++++++------------------------- 1 file changed, 30 insertions(+), 45 deletions(-) diff --git a/src/PluginContainer.js b/src/PluginContainer.js index 88898fd27..0fe5307d1 100644 --- a/src/PluginContainer.js +++ b/src/PluginContainer.js @@ -67,55 +67,40 @@ type State = { pluginKey: string, }; -function computeState(props: Props): State { - // plugin changed - let activePlugin = [NotificationsHub, ...devicePlugins].find( - (p: Class>) => p.id === props.selectedPlugin, - ); - let target = props.selectedDevice; - let pluginKey = 'unknown'; - if (activePlugin) { - pluginKey = `${props.selectedDevice.serial}#${activePlugin.id}`; - } else { - target = props.clients.find( - (client: Client) => client.id === props.selectedApp, - ); - activePlugin = clientPlugins.find( - (p: Class>) => p.id === props.selectedPlugin, - ); - if (!activePlugin || !target) { - throw new Error( - `Plugin "${props.selectedPlugin || ''}" could not be found.`, - ); - } - pluginKey = `${target.id}#${activePlugin.id}`; - } - - return { - activePlugin, - target, - pluginKey, - }; -} - class PluginContainer extends Component { - plugin: ?FlipperBasePlugin<>; - - constructor(props: Props) { - super(); - this.state = computeState(props); - } - - componentWillReceiveProps(nextProps: Props) { - if ( - nextProps.selectedDevice !== this.props.selectedDevice || - nextProps.selectedApp !== this.props.selectedApp || - nextProps.selectedPlugin !== this.props.selectedPlugin - ) { - this.setState(computeState(nextProps)); + static getDerivedStateFromProps(props: Props): State { + let activePlugin = [NotificationsHub, ...devicePlugins].find( + (p: Class>) => p.id === props.selectedPlugin, + ); + let target = props.selectedDevice; + let pluginKey = 'unknown'; + if (activePlugin) { + pluginKey = `${props.selectedDevice.serial}#${activePlugin.id}`; + } else { + target = props.clients.find( + (client: Client) => client.id === props.selectedApp, + ); + activePlugin = clientPlugins.find( + (p: Class>) => p.id === props.selectedPlugin, + ); + if (!activePlugin || !target) { + throw new Error( + `Plugin "${props.selectedPlugin || ''}" could not be found.`, + ); + } + pluginKey = `${target.id}#${activePlugin.id}`; } + + return { + activePlugin, + target, + pluginKey, + }; } + state: State = this.constructor.getDerivedStateFromProps(this.props); + plugin: ?FlipperBasePlugin<>; + refChanged = (ref: ?FlipperBasePlugin<>) => { if (this.plugin) { this.plugin._teardown();