代码之家  ›  专栏  ›  技术社区  ›  Muhammad Abdullah Shafiq

使用react native中的react导航在选项卡视图中的两个屏幕之间共享数据(数组)

  •  0
  • Muhammad Abdullah Shafiq  · 技术社区  · 7 年前

    我正在使用 react-navigation redux . 所以我有两个选项卡,每个选项卡都有自己的堆栈导航器,每个选项卡有一个屏幕。所以我需要 locations 在两个屏幕上。目前,我在两个屏幕上执行此操作:

    state = { locations: [] };
    
    componentDidMount() {
      this.getAllLocations();
    }
    
      async getAllLocations() {
        let locations = await this.getMoviesFromApi();
        this.setState({ locations });
      }
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   Bilaal Rashid abel406    7 年前

    reactn

    最棒的是你可以像state一样使用它。不需要provider或redux东西(尽管它提供了它)。它可以与react导航集成(最多需要修改一些源代码,添加一个“n”来react,并引用全局变量)。太棒了,我喜欢。

    我在做一篇关于medium的文章时一直在思考这个问题,因为lib在RN社区中并不流行,但是希望您能给它一个机会,这个库只有22KB,不到一个完整的组件。

        2
  •  2
  •   LHIOUI    6 年前

    如果您有一个单例对象:

    export default class SharedData {
      constructor(){
      if(SharedData.instance){
         return SharedData.instance;
       }
    
       this.state = {locations:[]};
       this.listners =[];
       SharedData.instance = this;
       return SharedData.instance;
     }
    
     setLocations(locations){
        this.state.locations = locations;
        this.listners.forEach(listner=>listner(this.state.locations));
     }
     getLocations(){
         return this.state.locations;
     }
     addListner(listner){
        this.listners.push(listner);
         return listner;
     }
     removeListner(listner){
       let index = this.listners.indexOf(listner);
       if(index > -1){
          this.listners.splice(index,1);
        }
     }
    } 
    

    然后在要访问共享位置的每个选项卡中,请声明:

    // get an instance of SharedData
    this.sharedData = new SharedData();
    // subscribe to locations changes
    this.listner = sharedData.addListner((locations)=>{
       this.setState({locations});
    });
    
     // set locations
     this.sharedData.setLocations([]);
    
      // unregister when destroying the component
      this.sharedData.removeListner(this.listner);
    
        3
  •  0
  •   Hend El-Sahli    7 年前

    unstated ... 设置起来很简单