首页 > 解决方案 > React Native:如何阻止地图标记在每次状态更新时重新渲染

问题描述

我有一个组件,它有一个地图,其中包含多个自定义标记,用于不同的位置,还有一个带有卡片的轮播用于这些相同的位置。当用户按下标记时,它应该显示标注并在标记旁边(但在标注之外)显示位置名称。

但是,因为我更新了 in 中的状态onRegionChangeComplete,如果用户移动地图然后快速按下标记(在状态从调用setStatein完成更新之前onRegionChangeComplete),那么标记将在触发事件之前重新渲染onPress,并且永远不会触发事件.

一种解决方案可能是使用shouldComponentUpdate,但是,文档声明它应该只用于性能优化而不是防止重新渲染(https://reactjs.org/docs/react-component.html#shouldcomponentupdate),但更多重要的是,我的componentDidUpdate函数有一些依赖于设置的区域的条件逻辑shouldComponentUpdate,以及其他条件操作,所以我不想阻止重新渲染整个组件,只是不必要地重新渲染标记。

我还使用了https://github.com/react-native-community/react-native-maps/issues/2082中提到的性能优化,将制造商包装在一个实现的组件中shouldComponentUpdategetDerivedStateFromProps但是,我不是完全确定这是在做任何事情,因为父组件似乎只是在重新创建我所有的优化标记,而不是使用它们的优化来处理重新渲染。此外,即使我不使用包装标记而是使用传统的自定义标记,我仍然遇到同样的问题。

我还在 react-native-maps 上为此打开了一个问题,但尚未得到回复:https ://github.com/react-native-community/react-native-maps/issues/2860

我的“onRegionComplete”函数在地图移动时更新状态。为简洁起见,我删除了其他一些条件状态更新:

onRegionChangeComplete = (region) => {
    const nextState = { };
    nextState.region = region;

    if (this.state.showNoResultsCard) {
      nextState.showNoResultsCard = false;
    }

    .
    .
    .

    this.setState({ ...nextState });

    this.props.setSearchRect({
      latitude1: region.latitude + (region.latitudeDelta / 2),
      longitude1: region.longitude + (region.longitudeDelta / 2),
      latitude2: region.latitude - (region.latitudeDelta / 2),
      longitude2: region.longitude - (region.longitudeDelta / 2)
    });
  }

MapView 使用更传统的标记(不是优化版本):

<MapView // show if loaded or show a message asking for location
    provider={PROVIDER_GOOGLE}
    style={{ flex: 1, minHeight: 200, minWidth: 200 }}
    initialRegion={constants.initialRegion}
    ref={this.mapRef}
    onRegionChange={this.onRegionChange}
    onRegionChangeComplete={this.onRegionChangeComplete}
    showsUserLocationButton={false}
    showsPointsOfInterest={false}
    showsCompass={false}
    moveOnMarkerPress={false}
    onMapReady={this.onMapReady}
    customMapStyle={mapStyle}
    zoomTapEnabled={false}
    >

        {this.state.isMapReady && this.props.places.map((place, index) => {
            const calloutText = this.getDealText(place, 'callout');
            return (
                <Marker
                    tracksViewChanges
                    key={Shortid.generate()}
                    ref={(ref) => { this.markers[index] = ref; }}
                    coordinate={{
                        latitude: place.getLatitude(),
                        longitude: place.getLongitude()
                    }}
                    onPress={() => { this.onMarkerSelect(index); }}
                    anchor={{ x: 0.05, y: 0.9 }}
                    centerOffset={{ x: 400, y: -60 }}
                    calloutOffset={{ x: 8, y: 0 }}
                    calloutAnchor={{ x: 0.075, y: 0 }}
                    image={require('../../Assets/icons8-marker-80.png')}
                    style={index === this.state.scrollIndex ? { zIndex: 2 } : null}
                >
               {this.state.scrollIndex === index &&
                    <Text style={styles.markerTitle}>{place.getName()}</Text>}

                  <Callout onPress={() => this.onCalloutTap(place)} tooltip={false}>
                    <View style={{
                      borderColor: red,
                      width: 240,
                      borderWidth: 0,
                      borderRadius: 20,
                      paddingHorizontal: 8,
                      flexDirection: 'column',
                      justifyContent: 'flex-start',
                      alignItems: 'center'
                    }}
                    >
                      <Text style={styles.Title}>Now:</Text>
                      <View style={{
                        width: 240,
                        flexDirection: 'column',
                        justifyContent: 'space-evenly',
                        alignItems: 'flex-start',
                        paddingHorizontal: 8,
                        flex: 1
                      }}
                      >
                        {calloutText.Text}
                    </View>
                </View>
            </Callout>
        </Marker>
        );
    }) 
}

</MapView>

我对标记的新闻事件的功能:

onMarkerSelect(index) {
    this.setState({ scrollIndex: index });
    this.carousel._component.scrollToIndex({
      index,
      animated: true,
      viewOffset: 0,
      viewPosition: 0.5
    });

    this.markers[index].redrawCallout();
}

更新状态然后快速按下标记将导致 onPress 事件不触发。此外,每次更新父组件时都会重新渲染/重新创建标记。(我说重新创建是因为标记似乎正在重新渲染,甚至没有触发shouldComponentUpdate 或componentDidUpdate)。

有没有办法在onRegionChangeComplete不强制标记重新渲染的情况下更新状态?

标签: reactjsreact-nativereact-native-iosreact-native-maps

解决方案


对于碰巧遇到此问题的其他任何人,问题在于我随机生成标记的键,导致父组件每次重新渲染时都会创建新标记。

具体来说,线路key={Shortid.generate()}是问题所在。


推荐阅读