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
This commit is contained in:
Daniel Büchele
2018-10-22 06:58:02 -07:00
committed by Facebook Github Bot
parent 86c796a706
commit 7b9bd8560e

View File

@@ -67,55 +67,40 @@ type State = {
pluginKey: string, pluginKey: string,
}; };
function computeState(props: Props): State {
// plugin changed
let activePlugin = [NotificationsHub, ...devicePlugins].find(
(p: Class<FlipperDevicePlugin<>>) => 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<FlipperPlugin<>>) => 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<Props, State> { class PluginContainer extends Component<Props, State> {
plugin: ?FlipperBasePlugin<>; static getDerivedStateFromProps(props: Props): State {
let activePlugin = [NotificationsHub, ...devicePlugins].find(
constructor(props: Props) { (p: Class<FlipperDevicePlugin<>>) => p.id === props.selectedPlugin,
super(); );
this.state = computeState(props); let target = props.selectedDevice;
} let pluginKey = 'unknown';
if (activePlugin) {
componentWillReceiveProps(nextProps: Props) { pluginKey = `${props.selectedDevice.serial}#${activePlugin.id}`;
if ( } else {
nextProps.selectedDevice !== this.props.selectedDevice || target = props.clients.find(
nextProps.selectedApp !== this.props.selectedApp || (client: Client) => client.id === props.selectedApp,
nextProps.selectedPlugin !== this.props.selectedPlugin );
) { activePlugin = clientPlugins.find(
this.setState(computeState(nextProps)); (p: Class<FlipperPlugin<>>) => 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<>) => { refChanged = (ref: ?FlipperBasePlugin<>) => {
if (this.plugin) { if (this.plugin) {
this.plugin._teardown(); this.plugin._teardown();