【问题标题】:initialRouteName of react-navigation does not work as expectedreact-navigation 的 initialRouteName 没有按预期工作
【发布时间】:2022-01-11 13:04:43
【问题描述】:

我正在使用 react-navigation v5,我有以下代码可以根据用户是否登录来打开屏幕。

<Stack.Navigator
        
        initialRouteName={phone?.length>0 ? data?.accountType === 1 ? "Seller" : data?.accountType === 0 ?  "Buyer" : "SignIn": "SignIn"}
        headerMode="screen"
        screenOptions={{
          headerShown: false,
        }}>
..........
 </Stack.Navigator>

电话数据和数据?.accountType 来自我的 componentDidMount() 内的 AsyncStorage。这样做是为了在他已经登录时打开卖家/买家页面,或者在他未登录时打开登录页面。但它总是带我到登录页面。是不是在 componentDidMount() 让我从 AsyncStorage 获取数据之前,initialRouteName 已经运行,因此 phone 和 data?.accountType 都为空?

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

    这是实现结果的简单方法

    constructor(props) {
        super(props)
        this.state = {
          initialRouteName: null,
        }
      }
    
      render() {
        const layout = this.Layout(this.state.initialRouteName);
        return (layout);
      }
    
      /** Layout */
      Layout =(initialRouteName)=> {
        if (initialRouteName !== null) {
          return (
            <NavigationContainer>
              <MainStack.Navigator initialRouteName={initialRouteName}>
                <MainStack.Screen name={"screen1"} component={screen1} />
                <MainStack.Screen name={"screen2"} component={screen2} />
              </MainStack.Navigator>
            </NavigationContainer>
          );
        } else {
          return (<View></View>);
        }
      }
    
      componentDidMount() {
        this.setState({initialRouteName: condition ? "screen1" : "screen2"});
      }
    

    【讨论】:

    • 非常感谢,这确实有帮助。只需要弄清楚在 else 块中显示而不是在白屏中显示是一个更好的选择。
    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 2017-04-04
    • 2021-09-03
    • 1970-01-01
    • 2022-08-16
    • 2021-05-07
    • 2020-08-04
    • 2019-01-19
    相关资源
    最近更新 更多