我在React Navigation网站上看到了Redux Integration page,但我不明白为什么我们需要在Redux商店中存储导航状态,我们只是将我们的应用程序状态存储在Redux中并让导航器保持自己的状态?
因为整合router.getStateForAction()
和router.getActionForPathAndParams()
似乎非常复杂。
getStateForAction()
吗?为他们创建一个减速器? router.getActionForPathAndParams()
?由于
答案 0 :(得分:2)
没有必要在reducer中存储导航状态。如果您不需要,只需将应用程序状态保持在reducer和navigation状态。然后你可以像这样集成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
包装每个组件,只需要根组件。在屏幕之间导航时,您无需发送/管理操作。它会自动更新。