如何从非组件辅助函数访问redux的存储? [英] How can you access redux's store from a non-component helper function?

查看:84
本文介绍了如何从非组件辅助函数访问redux的存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个帮助函数,当我想从我的redux商店中删除一些东西时,我会调用它。但是,我需要能够访问函数内的当前存储,以确定下一步该做什么。这就是我想要做的事情:

I have a a helper function that I call when I want to delete something from my redux store. However I need to be able to access the current store inside the function to make a determination on what to do next. Here's what I want to do:

export function deleteDocument (id) {
    this.props.dispatch(deleteShape({id}));

    const getStore = getStore(); //<-- I need something like this

    if(getStore.documents && !getStore.documents.find(doc => doc.selected)){
        this.props.dispatch(makeTopDocumentSelected());
    }
}

我从一个组件调用此函数并传递这个它的背景,所以如果你对此感到好奇,它将有机会发送。但是,如果我尝试引用我传递的道具,它在deleteShape调用之后不会更新,因为此函数没有连接(缺少更好的词)到redux存储。所以我的问题是:如何从非组件函数访问当前的redux存储?谢谢

I call this function from a component and pass the "this" context to it so it will have access to dispatch if you're curious about that. But if I try to reference a prop that I pass along it doesn't update after the "deleteShape" call because this function is not "connected" (for lack of a better word) to the redux store. So my question is this: how can I access the current redux store from non-component functions? Thanks

推荐答案

我必须说我认为从某个功能中随机访问商店是一种不好的做法,并且可能会产生一些副作用发生,但如果你必须这样做,这是一种可能的方式:

I must say that I think it's a bad practice to randomly access the store from some function, and some side effects may occur, but if you have to do it this is a possible way:

file:storeProvider.js

file: storeProvider.js

var store = undefined;

export default {
    init(configureStore){
        store = configureStore();
    },
    getStore(){
        return store;
    }
};

file:App.js

file: App.js

import { createStore } from 'redux';
import rootReducer from './rootReducer';
import storeProvider from './storeProvider';

const configureStore = () => createStore(rootReducer);
storeProvider.init(configureStore);
const store = storeProvider.getStore();

const App = () =>
    <Provider store={store} >
        <Stuff/>
    </Provider>

file:yourfunction.js

file: yourfunction.js

import storeProvider from './storeProvider';

export function deleteDocument (id) {
    this.props.dispatch(deleteShape({id}));

    const state = storeProvider.getStore().getState();

    if(state.documents && !state.documents.find(doc => doc.selected)){
        this.props.dispatch(makeTopDocumentSelected());
    }
}

这篇关于如何从非组件辅助函数访问redux的存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆