问题描述
我有一个辅助函数,当我想从我的 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());
}
}
我从一个组件调用这个函数并将this"上下文传递给它,这样如果你对此感到好奇,它就可以访问调度.但是,如果我尝试引用我传递的道具,它不会在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
推荐答案
我必须说,我认为从某些函数中随机访问 store 是一种不好的做法,可能会出现一些副作用,但如果你必须这样做这是一种可能的方式:
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:
文件:storeProvider.js
file: storeProvider.js
var store = undefined;
export default {
init(configureStore){
store = configureStore();
},
getStore(){
return store;
}
};
文件: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>
文件: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 的商店?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!