mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Fix cascading update (#54438)
Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/54438 # Changelog: [Internal] `LogBoxStateSubscription` subscribed to state updates in a mount effect. This callback could be called instantly on subscription initiation, which would cause a cascading update => setState in mount effect [1]. This diff changes the approach, the state is initialized before mount and the callback is not called synchronously on initialization. I had to keep `observe` function as it is right now, because it is used extensively in tests. Reviewed By: javache Differential Revision: D86449266 fbshipit-source-id: c7a2cffec760e697d8b5525e88997204b16fcd81
This commit is contained in:
1 parent
2a1e12f787
commit
84ee4d4643
1 file changed
+31
-4
+31
-4
@@ -412,6 +412,21 @@ export function observe(observer: Observer): Subscription {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as observe(), but doesn't call notify observer sync at the time of subscription.
|
||||
* Expected to be used only in LogBoxStateSubscription.
|
||||
*/
|
||||
function observeNext(observer: Observer): Subscription {
|
||||
const subscription = {observer};
|
||||
observers.add(subscription);
|
||||
|
||||
return {
|
||||
unsubscribe(): void {
|
||||
observers.delete(subscription);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type LogBoxStateSubscriptionProps = $ReadOnly<{}>;
|
||||
type LogBoxStateSubscriptionState = $ReadOnly<{
|
||||
logs: LogBoxLogs,
|
||||
@@ -447,12 +462,11 @@ export function withSubscription(
|
||||
}
|
||||
|
||||
_subscription: ?Subscription;
|
||||
_updateStateOnMountTimeoutId: ?TimeoutID;
|
||||
|
||||
state: LogBoxStateSubscriptionState = {
|
||||
logs: new Set(),
|
||||
isDisabled: false,
|
||||
hasError: false,
|
||||
selectedLogIndex: -1,
|
||||
...getNextState(),
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
@@ -472,12 +486,25 @@ export function withSubscription(
|
||||
}
|
||||
|
||||
componentDidMount(): void {
|
||||
this._subscription = observe(data => {
|
||||
this._subscription = observeNext(data => {
|
||||
this.setState(data);
|
||||
});
|
||||
|
||||
/**
|
||||
* This should cover the case when the state changes in between the first render and mount effect.
|
||||
* We defer the state update to next task to avoid cascading update.
|
||||
*/
|
||||
this._updateStateOnMountTimeoutId = setTimeout(() => {
|
||||
this._updateStateOnMountTimeoutId = null;
|
||||
this.setState(getNextState());
|
||||
}, 0);
|
||||
}
|
||||
|
||||
componentWillUnmount(): void {
|
||||
if (this._updateStateOnMountTimeoutId != null) {
|
||||
clearTimeout(this._updateStateOnMountTimeoutId);
|
||||
}
|
||||
|
||||
if (this._subscription != null) {
|
||||
this._subscription.unsubscribe();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user