简体   繁体   中英

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. 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. 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

var store = undefined;

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

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

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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