React redux 阻止从旧状态更新组件

React redux prevent updating component from old state

我有地图组件,地图中心位置连接到 redux 状态。

<YandexMapView
                ref={this._mapRef}
                location={this.props.location}
                onInteraction={(event) => this.onMapPositionChanged(event)}
                geocodingEnabled={true}
                onGeocoding={(event) => this.onGeocoding(event)}
            />

我的储蓄函数是

onMapPositionChanged(event: OnInteractionResult) {
    const {latitude, longitude} = event;
    this.props.dispatch(updateLocation({
        latitude, longitude,
    }));
}

当我移动地图,然后在短时间内再次移动它,在我的旧状态更新到组件之前我有无限抖动效果。

异常序列为:

  1. 组件发送事件以使用数据{纬度:1,经度:1}更新状态。

  2. 状态更新为{纬度:1,经度:1}。

  3. 那时组件发送另一个事件来更新 state = {latitude: 2、经度:2}因为我移动了地图。

  4. 组件在 props = {latitude: 1, longitude: 1}

  5. 中接收旧状态
  6. 组件将其地图位置更新为旧的{latitude: 1, longitude: 1}并再次发送{latitude: 1, longitude: 1}

所有这些动作都变成了无限...

我试图为我的 redux sagas 添加延迟或限制,但它没有帮助。

您需要将用户启动的地图移动事件与以编程方式移动地图生成的事件分开。您可能只想为来自 用户 移动地图的事件调用 onMapPositionChanged

您没有指定您使用的是哪个库,但是对于 React Native,例如doomsower/react-native-yandexmapkit 的 onInteraction 回调有一个 type attribute 可用于此目的。无论您使用的是什么库,都可能支持类似的东西。