简体   繁体   English

防止仅对组件的一部分更新 state 重新渲染

[英]Prevent re-render on state update for only one part of component

I'm using dynamic moving markers in my React-Native application, in order to make the markers move I've got state updates on an interval that re-renders the screen with the new marker positions.我在我的 React-Native 应用程序中使用动态移动标记,为了使标记移动,我在间隔上更新了 state,使用新标记位置重新渲染屏幕。 I'm also trying to use react-native-maps-directions which uses the google Routes API (which costs money) and I can't allow the routes API to get called twice every second because that seems wasteful (also because I'm poor).我也在尝试使用 react-native-maps-directions 它使用谷歌路线 API (这需要花钱),我不能让路线 API 每秒被调用两次,因为这似乎很浪费(也因为我较差的)。

Basically, do you know of a way to keep re-rendering the part that updates marker locations while not re-rendering the routes基本上,您是否知道一种方法可以继续重新渲染更新标记位置的部分而不重新渲染路线

Here's my render:这是我的渲染:

render() {
    return (
      <View>
          <MapView
            allOfMyProps={blahblahProps}
          >

            //This currently does and should re-render every time because I need them to move
            {this.state.markers[1] !== null &&
              this.state.markers.map((marker, index) => (
                <MapView.Marker
                  key={index}
                  coordinate={{
                    latitude: marker.coordinate.latitude,
                    longitude: marker.coordinate.longitude,
                  }}
                />
              ))}

            /// This is what renders the route, I want this to not re-render every time state changes
          <MapViewDirections
              origin={origin}
              destination={destination}
              apikey={GOOGLE_MAPS_API_KEY} //configure this right
              strokeWidth={10}
              strokeColor="green"
           />


          </MapView>
    </View>

I solved it by creating a new external class-based component and using another shouldComponentUpdate which tests to see if the destination prop updated.我通过创建一个新的基于外部类的组件并使用另一个 shouldComponentUpdate 来测试目标道具是否更新来解决它。 If it updated, then re-render the component, if not it'll send back what it already rendered.如果它更新了,则重新渲染组件,如果没有,它将发回它已经渲染的内容。 HUGE thanks to Drew Reese for the hint!非常感谢 Drew Reese 的提示!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM