How can you access redux's store from a non-co

2019-05-05 18:50发布

问题:

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

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

回答1:

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