如何在应用商店中调用Redux Action函数?

时间:2018-09-11 17:27:21

标签: reactjs redux

我从商店调用了 Redux 操作功能,但在 store.dispatch 上显示了错误 “ TypeError:__WEBPACK_IMPORTED_MODULE_6__store __。a.dispatch不是函数”。

App Store代码:

import store from './store';
    if (localStorage.getItem("persist:root")) {
      const persistData = localStorage.getItem("persist:root")
      const root = JSON.parse(persistData)
      const field = JSON.parse(root.auth)
      const expiresIn = field['authToken']["expiresIn"]

       //check expire date
      const currentTime = Date.now() / 1000;
      if(expiresIn<currentTime){
        store.dispatch(logoutUser());
        window.location.href='/login';
      }
    } 

Redux操作:

export const logoutUser = ()=>dispatch=>{
   //......
   dispatch(setCurrentUser({}));
}

创建商店:

const initialState = {};
const middleware = [reduxThunk];
const persistConfig = {
  key: 'root',
  storage,
  whitelist: ['auth'],
  blacklist: ['errors', 'profile', 'target']
};
const persistedReducer = persistReducer(persistConfig, rootReducer)
export default () => {
let store = createStore(
  persistedReducer,
  initialState,
  composeWithDevTools(
    applyMiddleware(...middleware),
  )
);
let persistor = persistStore(store);
return   { store, persistor };
};

Index.js:

import { Provider } from 'react-redux';
import configureStore from './store';
import { PersistGate } from 'redux-persist/integration/react';
const { persistor, store } = configureStore();
ReactDom.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
  , document.querySelector('#root')
);

1 个答案:

答案 0 :(得分:1)

因此,除了store.js文件之外,还要创建一个单独的文件,将其命名为newStore.js

newStore.js

import configureStore from './store';

const { persistor, store } = configureStore();

export { persistor, store }

修改索引文件

import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
--------------------------------
import { persistor, store } from './newStore'; //This is changed
--------------------------------
ReactDom.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
  , document.querySelector('#root')
);

将您的App Store代码修改为

import { store } from './newStore'; //This is changed

---------------------------
if (localStorage.getItem("persist:root")) {
  const persistData = localStorage.getItem("persist:root")
  const root = JSON.parse(persistData)
  const field = JSON.parse(root.auth)
  const expiresIn = field['authToken']["expiresIn"]

   //check expire date
  const currentTime = Date.now() / 1000;
  if(expiresIn<currentTime){
    store.dispatch(logoutUser());
    window.location.href='/login';
  }
} 

希望这会有所帮助。