简体   繁体   English

如何从非组件辅助函数访问redux的存储?

[英]How can you access redux's store from a non-component helper function?

I have aa helper function that I call when I want to delete something from my redux store. 当我想从我的redux商店中删除一些东西时,我有一个帮助函数。 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());
    }
}

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. 我从一个组件中调用此函数并将“this”上下文传递给它,以便在您对此感到好奇时可以访问dispatch。 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. 但是,如果我尝试引用我传递的道具,它在“deleteShape”调用之后不会更新,因为此函数没有“连接”(缺少更好的词)到redux存储。 So my question is this: how can I access the current redux store from non-component functions? 所以我的问题是:如何从非组件函数访问当前的redux存储? 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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM