React Native 中的 Redux 没有 Redux 中的 React Navigation 状态

Redux in React Native without React Navigation state in Redux

我在 React Navigation 网站上看到 Redux Integration page 但我不明白为什么我们需要在 Redux 存储中存储导航状态,我们不能只用 Redux 存储应用程序的状态并让导航器保持自己的状态?

因为整合router.getStateForAction()router.getActionForPathAndParams()似乎很复杂。

谢谢

不需要在reducer中存储导航状态。如果您不需要,只需将应用程序状态保持在 reducer 和导航状态。然后你可以像这样集成 Redux:

// App.js

import React from 'react';
import { Provider } from 'react-redux'
import RootNavigator from './src/navigation/RootNavigation';
import configureStore from './src/stores/configureStore';

const store = configureStore();

export default class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <RootNavigator />
      </Provider>
    );
  }
}

但实际上,在 Redux 中集成导航状态并没有那么复杂。如果您这样做,导航状态将在您在屏幕之间导航时自动更新。它在复杂的应用程序中非常有用。所以,我将尝试向您解释如何一起使用 React Navigation 和 Redux,也许您将来会发现它有用。

首先,您配置 StackNavigator as usual

// navigation/RootNavigator.js

const HomeScreen = () => (
  <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
    <Text>Home Screen</Text>
  </View>
);

const RootNavigator = StackNavigator({
  Home: {
    screen: HomeScreen,
  },
});

export default RootNavigator;

然后转到 reducers 文件夹(如果有)并创建 navReducer.js

 // reducers/navReducer.js

import RootNavigator from '../navigation/RootNavigation';

const initialState = RootNavigator.router.getStateForAction(RootNavigator.router.getActionForPathAndParams('Home'));

const navReducer = (state = initialState, action) => {
  const nextState = RootNavigator.router.getStateForAction(action, state);

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

我们使用 RootNavigator.router.getStateForAction 只是为了获取导航状态并将其设置为新减速器的初始状态。

然后把reducer和其他的结合起来:

// reducers/index.js

Import navReducer from ‘./navReducer’;

const appReducer = combineReducers({
  nav: navReducer,// updated was nav:nav,
  ...
});

现在我们只需要修改我们的App.js。现在它看起来像:

import React from 'react';
import { Provider, connect } from 'react-redux';
import { addNavigationHelpers } from 'react-navigation';
import RootNavigator from './src/navigation/RootNavigation';
import configureStore from './src/stores/configureStore';
const store = configureStore();

class AppComponent extends React.Component {
  render() {
    return (
      <RootNavigator navigation={addNavigationHelpers({
        dispatch: this.props.dispatch,
        state: this.props.nav,
      })} />
    );
  }
}

const mapStateToProps = (state) => ({
  nav: state.navReducer
});

const AppContainer = connect(mapStateToProps)(AppComponent);

export default () => {
  return (
    <Provider store={store}>
      <AppContainer />
    </Provider>
  )
}

所以,你不需要用 addNavigationHelpers 包裹每个组件,只需要根组件。在屏幕之间导航时,您不需要 send/manage 操作。会自动更新。