首页 > 解决方案 > MapBox 在 react native 中更新状态时不会更改 renderAnnoations ( setState(..) , forceUpdate() 对它没有影响)

问题描述

正如您在此代码中看到的那样,每次调用数据过滤器按钮之一的 onPress 时,我都会更改 Mapbox 中的渲染注释:

import MapboxGL from "@react-native-mapbox-gl/maps";

MapboxGL.setAccessToken("mytoken_workign_fine");

export default class myClass extends Component{
  render_annotaions1 = [{.....},{.....},....];
  render_annotaions2 = [{.....},{.....},....];
  render_annotaions3 = [{.....},{.....},....];
  
   constructor(props) {
      super(props);
      this.state = {
        filter_state: 1,
      };
    }
  
  press_filter1(){
    if(this.state.filter_state != 1){
      this.setState({filter_state:1});
    }
  }
  
  press_filter2(){
  if(this.state.filter_state != 2){
    this.setState({filter_state:2});
  }
  }
  
  press_filter3(){
  if(this.state.filter_state != 3){
    this.setState({filter_state:3});
  }
  }
  
  getAnnotations(){
  switch(this.state.filter_state ){
    case 1:return this.render_annotaions1;
    case 2:return this.render_annotaions2;
    default:return this.render_annotaions3;
  }
  }
  render(){
  return (
    <MapboxGL.MapView
                  ref={(c) => (this._map = c)}
                  style={{ flex: 1 }}
                  rotateEnabled={false}
                  logoEnabled={false}
                  userTrackingMode={1}
                  pitchEnabled={false}
                >
                  {this.getAnnotations()}
                  <MapboxGL.Camera
                    zoomLevel={1.1}
                    followUserLocation={false}
                    centerCoordinate={[9, 34]}
                  />
                </MapboxGL.MapView>);
  }
}

现在,默认注释( annotations1 )显示良好,但是当我按下一个过滤器按钮时,没有地图更改,它保留默认注释,这是我的问题,我想通过getAnotaions()返回的新闻分配注释更改集合注释

设置状态()

强制性升级()

打电话(两者都不工作),请我需要帮助解决这个问题,谢谢大家。

标签: javascriptandroidreact-nativemapboxmapbox-gl

解决方案


在 React 中使用class组件时,需要在构造函数中绑定方法才能访问this. 在这里阅读:https ://reactjs.org/docs/handling-events.html

   constructor(props) {
      super(props);
      this.state = {
        filter_state: 1,
      };

      this.press_annotation1 = this.press_annotation1.bind(this);
    }

您需要为每个点击处理程序执行此操作。

我还建议使用处于过滤器状态的单击处理程序。就像是:

  setFilterState(annotationNumber) {
    this.setState({ filter_state: annotationNumber });
  }

最后,总是用大写字母命名你的 React 组件。


推荐阅读