【问题标题】:Navigating between components reloads all components in navigator routes在组件之间导航会重新加载导航器路由中的所有组件
【发布时间】:2017-07-11 07:28:27
【问题描述】:

我在某处读到过,当您使用 react-navigation 包中的任何导航器并且您实现了 redux 时;导航器路线中的每个组件都将被重新加载(即componentWillRecieveProps

但是,我有两个用户可以登录的页面

export const MainScreenTabNavigator = TabNavigator({
    Start: {
        screen: Start,
        navigationOptions: {
            title: 'Start',
        },
    },
},{
    tabBarPosition: "bottom",
    tabBarOptions: {
        activeTintColor: '#222',
        labelStyle: {
            color: '#ddd',
        },
        style: { backgroundColor: '#333' },
    }
});

export const AppNavigator = StackNavigator({
    Main: {
        screen: MainScreenTabNavigator, // Nested tab navigator
    },
    Login: {
        screen: Login,
        navigationOptions: {
            title: 'Aanmelden',
        }
    },
    Camera: {
        screen: AppCamera,
        navigationOptions: {
            title: 'Camera',
        }
    }

}, {
    mode: 'modal',
    headerMode: 'none',
});

登录屏幕最初显示给用户。它有一个表单,用户可以在其中手动输入凭据,还有一个按钮可以导航到摄像头,用户可以在其中扫描带有登录凭据的二维码。

在这两种情况下,用户都会发送登录操作。 登录页面和相机页面都监听相同的道具变化:

componentWillReceiveProps(nextProps) {
    if (nextProps.account.loginSuccess) {
        this.props.navigation.dispatch(NavigationActions.navigate({ routeName: 'Start' }));
    } else {
        if (nextProps.account.loginError) {
            Toast.showLongBottom(nextProps.loginError);
        }
    }
    this.setState({spinnerVisible: false});
}

应用程序成功导航到“开始”,但是当它完成时,登录和相机页面都被重新加载,导致进入componentWillReceiveProps 的无限循环,并一遍又一遍地无限导航到“开始”。

这是我的导航减速器:

function nav(state = initialNavState, action) {
    const nextState = AppNavigator.router.getStateForAction(action, state);

    // Simply return the original `state` if `nextState` is null or undefined.
    return nextState || state;
}

我可以做些什么来防止这种行为?

【问题讨论】:

    标签: android react-native react-redux react-navigation


    【解决方案1】:

    嗯,

    作为临时解决方案,我在导航状态中引入了另一个布尔值:

    function nav(state = initialNavState, action) {
        let nextState = null;
    
        if (action.type === 'Navigation/NAVIGATE' && action.routeName === 'Start') {
            nextState = {...AppNavigator.router.getStateForAction(action, state), authenticated: true};
        } else {
            nextState = AppNavigator.router.getStateForAction(action, state);
        }
    
        // Simply return the original `state` if `nextState` is null or undefined.
        return nextState || state;
    }
    

    我使用authenticated 来检查登录或相机组件是否应该在登录后导航到启动。

    它有效,但我仍然觉得我错过了一些东西。

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 2019-09-06
      • 2018-03-30
      • 2021-12-20
      • 2019-06-02
      • 2020-08-24
      • 2023-03-22
      • 2020-07-03
      相关资源
      最近更新 更多