【问题标题】:MapBox dosn't change renderAnnoations when update state in react native ( setState(..) , forceUpdate() have no effect to it )MapBox 在 react native 中更新状态时不会更改 renderAnnoations( setState(..) , forceUpdate() 对其没有影响)
【发布时间】:2020-07-04 21:37:11
【问题描述】:

每次 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 ) 显示良好,但是当我按下一个过滤器按钮时,没有地图更改,它保留默认注释,这是我的问题,我想通过 getAnnotations() 每一个

setState()

和

forceUpdate()

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

【问题讨论】:

    标签: javascript android react-native mapbox mapbox-gl


    【解决方案1】:

    在 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 组件。

    【讨论】:

    • 嘿,谢谢您的回答,所有事件处理程序都可以在没有绑定的情况下正常工作,并且我的所有过滤器方法都会在我需要时调用,我需要如何在我的 Mapbox 上应用所需的注释更改。
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    相关资源
    最近更新 更多