当我想从我的redux商店中删除一些东西时,我有一个帮助函数.但是,我需要能够访问函数内的当前存储,以确定下一步该做什么.这就是我想要做的事情:
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()); } }
我从一个组件中调用此函数并将"this"上下文传递给它,以便在您对此感到好奇时可以访问dispatch.但是,如果我尝试引用我传递的道具,它在"deleteShape"调用之后不会更新,因为此函数没有"连接"(缺少更好的词)到redux存储.所以我的问题是:如何从非组件函数访问当前的redux存储?谢谢
我必须说我认为从某个函数中随机访问商店是一种不好的做法,但如果你必须这样做,这是一种可能的方法:
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 = () =>
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()); } }