问题
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.
- FavoritesView: display saved data
- ExploreView: Manipulate saved data
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