在致电createReduxContainer
之前,请致电createReactNavigationReduxMiddleware
,以便我们知道何时触发您的听众
答案 0 :(得分:0)
这是react-navigation(v3)和Redux的经过测试的示例。此处,反应导航已集成到Redux中。但是,我拒绝再使用此方法。我认为,在使事情变得更加复杂时,集成是不必要的。
App.JS文件:
import React, {Component} from 'react';
import { Provider } from "react-redux";
import { createStore, applyMiddleware, combineReducers } from "redux";
import { createStackNavigator } from "react-navigation";
import {
reduxifyNavigator,
createReactNavigationReduxMiddleware,
createNavigationReducer
} from "react-navigation-redux-helpers";
import MainScreen from "./Screens/MainScreen";
import SignUpScreen from "./Screens/SignUpScreen";
import rootReducer from "./src/rootReducer";
import ReduxNavigation from "./src/ReduxNavigation";
import { Directions } from 'react-native-gesture-handler';
const AppNavigator = createStackNavigator(
{
// LoginScreen: { screen: LoginScreen },
MainScreen: { screen: MainScreen },
SignUpScreen: { screen: SignUpScreen }
},
{
initialRouteName: "SignUpScreen"
}
);
const navReducer = createNavigationReducer(AppNavigator);
const appReducer = combineReducers({
nav: navReducer,
app: rootReducer
});
const middleware = createReactNavigationReduxMiddleware(
"root",
state => state.nav
);
export const AppNav = reduxifyNavigator(AppNavigator, "root");
const store = createStore(appReducer, applyMiddleware(middleware));
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<Provider store={store}>
<ReduxNavigation />
</Provider>
);
}
}
ReduxNavigation.js:
import React from "react";
import { BackHandler } from "react-native";
import { connect } from "react-redux";
import { NavigationActions } from "react-navigation";
import { AppNav } from "../App";
class ReduxNavigation extends React.Component {
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
}
onBackPress = () => {
const { nav, dispatch } = this.props;
if (nav.index === 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
};
render() {
const { nav, dispatch } = this.props;
return <AppNav state={nav} dispatch={dispatch} />;
}
}
const mapStateToProps = state => ({
nav: state.nav
});
export default connect(mapStateToProps)(ReduxNavigation);