我需要使用组件外部的存储值。
基本上我有这个:
// imports
import HomeScreen from '../screens/HomeScreen/HomeScreen';
import SettingsScreen from '../screens/SettingsScreen/SettingsScreen';
import FRoute from '../screens/HomeScreen/HomeScreen';
import SRoute from '../screens/SettingsScreen/SettingsScreen';
const HomeStack = createStackNavigator({
PickupHome: HomeScreen,
});
const SettingsStack = createStackNavigator({
PickupSettings: SettingsScreen,
});
export default createBottomTabNavigator({
HomeStack,
SettingsStack,
});
如您所见,它不是组件。这是一个包含我的路线的文件。它名为MainTabNavigator。 有了它,我需要执行以下操作:
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import HomeScreen from '../screens/HomeScreen/HomeScreen';
import SettingsScreen from '../screens/SettingsScreen/SettingsScreen';
import FRoute from '../screens/HomeScreen/HomeScreen';
import SRoute from '../screens/SettingsScreen/SettingsScreen';
const HomeStack = createStackNavigator({
// HERE I NEED TO USE THE VALUE FROM THE STORE
PickupHome: valueFromStore ? HomeScreen : FRoute,
});
const SettingsStack = createStackNavigator({
// HERE I NEED TO USE THE VALUE FROM THE STORE
PickupSettings: valueFromStore ? SettingsScreen : SRoute,
});
export default createBottomTabNavigator({
HomeStack,
SettingsStack,
});
如您所见,我没有办法打电话给connect
或任何一种我可以打电话给商店并将其作为道具传递的东西,就像我们通常做的那样。
这是我做过的减速器:
import createReducer from '../../../redux/createReducer';
import ActionTypes from '../constants/ActionTypes';
const initialState = {
navigation: {
index: 0,
routes: [
{ key: '1', title: 'Title 1' },
{ key: '2', title: 'Title 2' },
],
},
};
const handlers = {
[ActionTypes.INDEX_ROUTE](state, action) {
return {
...state,
navigation: {
...state.navigation,
index: action.payload.index,
},
};
},
};
export default createReducer(initialState, handlers);
动作:
import ActionTypes from '../constants/ActionTypes';
export const indexRouteAction = index => ({
type: ActionTypes.INDEX_ROUTE,
payload: {
index,
},
});
export default indexRouteAction;
例如:我正在另一个组件上使用该存储,并且可以这样访问其值:
export default compose(
connect(
store => ({
navigationStore: store.homeScreen.navigation,
}),
dispatch => ({
indexRouteActionHandler: data => {
dispatch(indexRouteAction(data));
},
}),
),
)(withNavigation(TopTabView));
所以我可以从那里获取值,仅此而已。
那我该怎么做才能在我最初发布的文件中获取该存储的值?
更新:
我正在阅读以下内容:https://redux.js.org/api/store#getState 但是我不知道如何使它适应我的代码,也不知道这是否适合我的情况。有什么见解吗?
答案 0 :(得分:2)
您将在代码中的某处创建存储,如下所示:
const store = createStore( ..reducers);
导出此同伴,导入要访问商店的位置,然后
store.getState().item // You can access store data