gpt4 book ai didi

javascript - 如何从组件外部的 Redux 存储中获取值?

转载 作者:行者123 更新时间:2023-12-01 01:16:10 26 4
gpt4 key购买 nike

我需要使用组件外部存储的值。

基本上我有这个:

// 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或任何可以调用商店并将它们作为 Prop 传递的事情,就像我们通常做的那样。

这是我做的 reducer :

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但我不知道如何使其适应我的代码,也不知道这是否是适合我的情况的解决方案。有什么见解吗?

最佳答案

您将在代码中的某个位置创建商店,如下所示:

const store = createStore( ..reducers);

导出这个家伙,导入你想要访问商店的地方,然后

store.getState().item // You can access store data

关于javascript - 如何从组件外部的 Redux 存储中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54743617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com