React Native: Force reload of TabBarIOS.item

限于喜欢 提交于 2019-12-21 17:27:30

问题


I have a TabBar based app in React Native. Multiple tabs use the same datasource (AsyncStorage). If I'm now updating the data in one tab and open the other one, the old data is displayed. I can't figure out, how to force a reload every time the item become active.

  1. FavoritesView: display saved data
  2. ExploreView: Manipulate saved data
  3. FavoritesView: expired data gets displayed (--> force reload)

    <TabBarIOS.Item
    title="Explore"
    icon={{uri:'ic_explore'}}
      selected={this.state.selectedTab === 'exploreTab'}
      onPress={() => {
        this.setState({
          selectedTab: 'exploreTab'
        });
      }}>
      <ExploreView/>
    </TabBarIOS.Item>
    
    <TabBarIOS.Item
      title="Favorites"
      icon={{uri:'ic_favorite_border'}}
      selected={this.state.selectedTab === 'favoriteTab'}
      onPress={() => {
        this.setState({
          selectedTab: 'favoriteTab'
        });
      }}>
       // Reload this
      <FavoritesView/>
    </TabBarIOS.Item>
    
    <TabBarIOS.Item
      systemIcon="more"
      selected={this.state.selectedTab === 'moreTab'}
      onPress={() => {
        this.setState({
          selectedTab: 'moreTab'
        });
      }}>
      <MoreView/>
    </TabBarIOS.Item>
    

I already tried to set a new state to trigger an update, but it doesn't seem to change anything.

<TabBarIOS.Item
      title="Favorites"
      icon={{uri:'ic_favorite_border'}}
      selected={this.state.selectedTab === 'favoriteTab'}
      onPress={() => {
        this.setState({
          selectedTab: 'favoriteTab',
          forceUpdate: Math.random()
        });
      }}>
      <FavoritesView forceUpdate={this.state.forceUpdate}/>
</TabBarIOS.Item>

回答1:


I had a similar issue and what eventually worked for me was to override componentWillReceiveProps on the embedded views. It gets called anytime the view is set as selectedTab in the TabBarIOS.

https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops




回答2:


this references the parent component when using fat arrow notation (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this).

Try adding a ref to the TabBar item and use this.refs.refName.forceUpdate() (slightly nicer than updating the state with a random value as well).



来源:https://stackoverflow.com/questions/31015045/react-native-force-reload-of-tabbarios-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!