从实用程序模块访问Redux存储

时间:2018-04-26 00:04:52

标签: reactjs react-redux axios

我正在尝试将我的商店导出到文件,以全局配置 Axios 。具体来说,在公共授权头中从商店注入令牌。该应用程序使用 weback-dev-server 在本地运行。

以下是应用入口点的代码:

import React from 'react';
import ReactDOM from 'react-dom';
import createHistory from 'history/createBrowserHistory';
import { createStore, compose, applyMiddleware } from 'redux';
import { ConnectedRouter, routerMiddleware } from 'react-router-redux';
import { Route } from 'react-router';
import Promise from 'redux-promise';
import ReduxThunk from 'redux-thunk';
import { Provider } from 'react-redux';
import { logger } from 'redux-logger';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';

import reducers from './reducers';
import Header from './components/Header.component';

const history = createHistory();
const middleware = [ Promise, ReduxThunk, logger ];
const store = createStore(
   reducers,
   undefined,
   compose(applyMiddleware(...middleware, routerMiddleware(history)))
);

export default store;

const App = () => (
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <div>
                <Header />
            </div>
        </ConnectedRouter>
</Provider>
);

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

以下是配置Axios的文件:

import axios from 'axios';

import store from '../src/main';

const select = state => state.auth.token;

const handleStoreChanges = () => {
const token = select(store.getState());
axios.defaults.headers.common.Authorization = `Bearer ${ token }`;
};
 store.subscribe(handleStoreChanges);

const api = axios.create({
baseURL: process.env.ADMIN_BASE_URL
 });

export default api;

当我尝试导入api时,我收到以下错误,因为store未定义 - 导致我相信导入在实例化之前可能已解决? - :

  

未捕获的TypeError:无法读取未定义的属性“subscribe”

1 个答案:

答案 0 :(得分:1)

有几种方法可以解决这个问题,但一种简单的方法是使用函数注入商店。

// axios file

import axios from 'axios';

const select = state => state.auth.token;

const api = axios.create({
  baseURL: process.env.ADMIN_BASE_URL
});

export const injectStore = store => {
  store.subscribe(() => {
    const token = select(store.getState());
    axios.defaults.headers.common.Authorization = `Bearer ${ token }`;
  })
}

export default api;

// store file

import { injectStore } from './api'

const store = createStore();

injectStore(store)

然而,对我来说更有意义的是api文件不知道商店,而是导出setter

// axios file

import axios from 'axios';

const api = axios.create({
  baseURL: process.env.ADMIN_BASE_URL
});

export const tokenSelector = state => state.auth.token;

export const setAuthHeader = token => {
  axios.defaults.headers.common.Authorization = `Bearer ${ token }`;
}

export default api;

// store file

import { tokenSelector, setAuthHeader } from './api'

const store = createStore();

store.subscribe(() => {
  const token = tokenSelector(store.getState());
  setAuthHeader(token)
})