简体   繁体   中英

Prevent navigating when double press button quickly react-native

Hi I am have code with react-navigation. I want to prevent navigating twice when clicking a button quickly. This code is working perfectly. This is my SignedOut Navigation

export const SignedOut = StackNavigator({
    Onboarding: {
        screen: Onboarding,
        navigationOptions: {
            title: "Onboarding",
            header: null
        }
    },
    InitApp: {
        screen: InitApp,
            navigationOptions: {
            title: "Init",
            header: null
        }
    },
    Auth: {
        screen: Auth,
        navigationOptions: {
            title: "Auth",
            header: null
        }
    }
});
const navigateOnce = (getStateForAction) => (action, state) => {
        const {type, routeName} = action;
        return (
        state &&
            type === NavigationActions.NAVIGATE &&
            routeName === state.routes[state.routes.length - 1].routeName
    ) ? null : getStateForAction(action, state);       
};
SignedOut.router.getStateForAction = navigateOnce(SignedIn.router.getStateForAction);

It is working perfectly. But today I want to add params to StackNavigator and navigateOnce didn't work!

The code like this:

export const SignedOuts = (firstTime = false) =>
    StackNavigator({
        Onboarding: {
        screen: Onboarding,
        navigationOptions: {
            title: "Onboarding",
            header: null
        }
    },
    InitApp: {
        screen: InitApp,
            navigationOptions: {
            title: "Init",
            header: null
        }
    },
    Auth: {
        screen: Auth,
        navigationOptions: {
            title: "Auth",
            header: null
        }
     }
    },
    {
        initialRouteName: firstTime ? "Onboarding" : "Auth",            
    }
)

It said: Cannot read property 'getStateForAction' of undefined

What should I do?

If you are using navigate method, and you want to prevent navigation twice(ie prevent a screen from being pushed twice), then, you should set the key of the screen.

this.props.navigation.navigate({'key':'NewsFeed', routeName:'NewsFeedScreen'})

I have not used routers with react-navigation and the document seems pretty scarce. My suggestion would be to go through the code of StackRouter here and look how you can pass a unique key to each screen. This should prevent the problem you are facing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM