用react-navigation的同学是不是经常遇到多次点击会跳转多次的bug,查询了下,有网友给出了改源码延时的方法,有的给出拦截的方法,我这边也有一种方式可以参考.基本原理也是拦截,但是只要几行代码,而且不用改源码.
代码如下:
import React from "react";
import { StyleSheet, Text, View } from 'react-native';
import { StackNavigator ,NavigationActions } from 'react-navigation';
import { Constants } from 'expo';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
return <Text>Hello, Navigation!</Text>;
}
}
const SimpleApp = StackNavigator({
Home: { screen: HomeScreen },
});
//主要是这一步
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);
};
在V2以上的版本,需要这么改,感谢[KingTortoise]同学指出: (type === NavigationActions.NAVIGATE || type === StackActions.PUSH)
//这是第二步
SimpleApp.router.getStateForAction = navigateOnce(SimpleApp.router.getStateForAction);
export default class App extends React.Component {
render() {
return (
<View>
<Text>Im App</Text>
<SimpleApp />
</View>
);
}
}