如何"lazy load"选项卡导航器屏幕,现在懒惰已从反应导航中删除



react-navigation 的维护者已经从库中删除了 'lazy: true',导致所有选项卡尝试立即渲染(并且获取以前由 lazy 控制的现在无序触发(。

为了保持类似的功能,如何在第一次聚焦之前强制在选项卡屏幕上强制等待不加载或调用取回调用?

似乎他们确实删除了它,但决定将其重新添加到 v 1.1.2 中

https://github.com/react-navigation/react-navigation/releases/tag/v1.1.2

因此,您应该能够在TabNavigatorConfig对象中传递lazy={true},然后选项卡在处于活动状态之前将不会呈现。要进一步优化内存使用,您可以将其与removeClippedSubviews结合使用,以从非活动选项卡中释放内存。

你可以使用 react-navigation-utils 中的LazyLoading

React-navigation现在支持withNavigationFocus包装器。您可以使用它来包装要阻止在未聚焦时更新的屏幕。

import React from 'react';
import { Text } from 'react-native';
import { withNavigationFocus } from 'react-navigation';
class LazyScreen extends React.Component {
   shouldComponentUpdate(nextProps, nextState) {
     return nextProps.isFocused;
   }
  render() {
    return <Text>{this.props.isFocused ? 'Focused' : 'Not focused' </Text>;
  }
}
export default withNavigationFocus(LazyScreen);

附言如果你使用Redux,就做 export default connect(mapStateToProps, mapDispatchToProps)(withNavigationFocus(LazyScreen));

lazy={true}
  optimizationsEnabled={true}
  tabBarOptions={tabBarOptions}

上面的代码很重要,试试吧

import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
import { createStackNavigator } from "@react-navigation/stack";
const TabNavigator = createMaterialTopTabNavigator();
const Stack1 = createStackNavigator();
const Stack2 = createStackNavigator();
const ProductsScreen = (props) => {
//
return (
<TabNavigator.Navigator
  lazy={true}
  optimizationsEnabled={true}
  tabBarOptions={tabBarOptions}
>
  <TabNavigator.Screen name="HOME" component={StackScreen1} />
  <TabNavigator.Screen name="SHOP" component={StackScreen2} />
</TabNavigator.Navigator>
);
};
const tabBarOptions = {
indicatorStyle: {
height: null,
top: 0,
backgroundColor: "#ccc",
borderBottomColor: "black",
borderBottomWidth: 3,
},
activeTintColor: "black",
style: {
backgroundColor: "red",
},
labelStyle: { fontSize: 13 },
};

这个怎么样?

const MyTab = TabNavigator({
    tab1:{screen:TabScreen1},
    tab2:{screen:TabScreen2}
}

class MainScreen extends React.Component{
    constructor(){
        super();
        this.state = {
            loading:true
        }
    }
    componentWillMount(){
        //fetch login
        //set loading:false when fetch is done
    }
    render(){
        !this.state.loading && <MyTab/>
    }
}

在新版本的 React Navigation 中,默认情况下,lazy prop 设置为 true

见 https://reactnavigation.org/docs/en/bottom-tab-navigator.html#lazy

最新更新