From 8a93b81005f7f72e97665d3535e5e20c5716ee9e Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Fri, 9 Jul 2021 22:17:52 +0800 Subject: [PATCH] use getDerivedStateFromProps to count refs --- package.json | 2 +- src/style.js | 34 +++++++++++++--------------------- 2 files changed, 14 insertions(+), 22 deletions(-) diff --git a/package.json b/package.json index 7b2b36e5..09587fd4 100644 --- a/package.json +++ b/package.json @@ -91,7 +91,7 @@ "xo": "0.24.0" }, "peerDependencies": { - "react": "15.x.x || 16.x.x || 17.x.x" + "react": "16.x.x || 17.x.x" }, "keywords": [ "babel-plugin-macros", diff --git a/src/style.js b/src/style.js index 96a2d8d8..31367b7f 100644 --- a/src/style.js +++ b/src/style.js @@ -6,7 +6,7 @@ const styleSheetRegistry = new StyleSheetRegistry() export default class JSXStyle extends Component { constructor(props) { super(props) - this.prevProps = {} + this.state = {} } static dynamic(info) { @@ -19,14 +19,18 @@ export default class JSXStyle extends Component { .join(' ') } - // probably faster than PureComponent (shallowEqual) - shouldComponentUpdate(otherProps) { - return ( - this.props.id !== otherProps.id || - // We do this check because `dynamic` is an array of strings or undefined. - // These are the computed values for dynamic styles. - String(this.props.dynamic) !== String(otherProps.dynamic) - ) + static getDerivedStateFromProps(props, state) { + if ( + props.id !== state.id || + String(props.dynamic) !== String(state.dynamic) + ) { + if (state.id) { + styleSheetRegistry.remove(state) + } + styleSheetRegistry.add(props) + return props + } + return null } componentWillUnmount() { @@ -34,18 +38,6 @@ export default class JSXStyle extends Component { } render() { - // This is a workaround to make the side effect async safe in the "render" phase. - // See https://github.com/zeit/styled-jsx/pull/484 - if (this.shouldComponentUpdate(this.prevProps)) { - // Updates - if (this.prevProps.id) { - styleSheetRegistry.remove(this.prevProps) - } - - styleSheetRegistry.add(this.props) - this.prevProps = this.props - } - return null } }