问题
Let's say there is a tab view which has tabs with names Breads, Pizzas, Beverages, Desserts, Shakes. And the name of these tabs are fetched from API. Also, the information for each tab to show on their respective screens is fetched from the API too. Now, when one of the Tab's data gets deleted from the API. I want it to be removed from the Tab View too.
How can I achieve this in React Navigation?
回答1:
In react navigation we cannot have dynamic tab, as we have to define all the routes statically well in advance.
We had such requirement too, so we followed the below mentioned approach.
- Define all the possible tabs statically and make tabs invisible.
const MainNav = createBottomTabNavigator( { Breads: { screen: BreadsStackNavigation }, Pizzas: { screen: PizzasStackNavigation }, Beverages: { screen: BeveragesStackNavigation }, Desserts: { screen: DessertsStackNavigation }, Shakes: { screen: ShakesStackNavigation } }, { initialRouteName: 'HomeStackNavigation', defaultNavigationOptions: { tabBarVisible: false, }, swipeEnabled: false, navigationOptions: { header: props => <HeaderView navigation={props.navigation} />, tabBarVisible: false } } );
- In the HeaderView, in
componentWillReceiveProps
check the response from the server and accordingly create tabs dynamically (may be by adding buttons dynamically depending on the responses).
UPDATE
I am thinking about one more approach.
As given in this link we can create our own custom navigator, and populate the tabs dynamic in the parent custom navigator after getting response from the API call. I do not have the exact code for the same, but you can try this approach.
回答2:
You can create a function that maps the server response to RouteConfigs and call the function in the render method.
WARNING. using this approach is very risky because, on every re-render, the navigator is regenerated. If you can tweak your View no to re-render after creating the tabs, then you can get away with this approach.
const mapArrayToTabs = (myArray) =>{
let result = {}
myArray.map( (item,index) =>{
result[item] = {
screen: ()=> <YourComponent/>,
navigationOptions: {...}
}
} )
return result
}
const createCustomTabs =()=>{
const MyTabs = createAppContainer(
createMaterialTopTabNavigator(
mapArrayToTabs(["Screen1", "Screen2"] ),
tabBarOptions: {...}
)
)
return <MyTabs/>
}
render(){
<View>
{this.createCustomTabs()}
</View>
}
来源:https://stackoverflow.com/questions/56901548/how-can-i-create-or-delete-tabs-in-react-navigation-based-on-the-data-fetched-fr