![](/img/trans.png)
[英]How to manage state of React-Navigation without Redux, React Native
[英]Redux in React Native without React Navigation state in Redux
我在React Navigation网站上看到了Redux集成页面 ,但是我不明白为什么我们需要在Redux商店中存储导航状态,我们不能只通过Redux存储应用程序的状态并让导航器保持自己的状态吗?
因为集成router.getStateForAction()
和router.getActionForPathAndParams()
看起来非常复杂。
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:
// 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
来包装每个组件,而只需使用根组件即可。 在屏幕之间导航时,您无需发送/管理操作。 它将自动更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.