如何使用父组件的redux store

问题描述 投票:0回答:2

我正在创建一个组件(-子组件),例如

npm package
(-另一个项目)。该组件将在另一个组件(- 父组件)中使用(将像
npm i child
一样安装)。

所以,我的问题是我想在孩子中使用 redux 存储架构。在父级中,有一个太redux存储架构。在孩子中,我不想使用自己的存储我想使用父组件的存储。我怎样才能做到这一点?如何在我的孩子中使用父组件的存储?

有可能吗?我不知道该怎么做。

感谢您的帮助。

reactjs redux
2个回答
1
投票

我认为还有更多一种方法可以做到这一点。

我更喜欢使用联合减速器的方式。

在您的子应用程序中创建一些减速器:

import {ACTIONS} from './actions';

const defaultState = {
    counter: 0,
};

export default function(state = defaultState, action) {
    switch (action.type) {
        case ACTIONS.PLUS:
            let newState = {...state};
            newState.counter++;
            return newState;
        case ACTIONS.MINUS:
            let newState2 = {...state};
            newState2.counter--;
            return newState2;
        default:
            return state;
    }
};

从项目中导出该减速器:

export {default as YourReducer} from './your-reducer'

现在,在父根减速器中组合此减速器:

import {combineReducers} from 'redux'

import app from 'app/containers/app/app-reducer'
import {YourReducer} from '@this-is-your-package/YourReducer'

export default combineReducers({
    app,
    YourReducer,
})

所以,就这样,现在您可以在您的孩子中使用

connect
mapStateToProps
dispatchToProps
等...。

您也可以读取父状态存储..

母店看起来像这样:

app: { ... }         // <-- parent
YourReducer: { ... } // <-- your child

1
投票

我可以建议你两个选择:
1) 为你的子组件创建一个reducer,并将其传递给reducer配置中的

combineReducer
。然后您就可以访问全球商店了。
2)或者你可以简单地将你的孩子从父组件消耗的任何东西作为道具传递。

© www.soinside.com 2019 - 2024. All rights reserved.