首页 > 解决方案 > 从实用程序模块访问 Redux 存储

问题描述

我正在尝试将我的商店导出到文件,以全局配置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;

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

未捕获的类型错误:无法读取未定义的属性“订阅”

标签: reactjsreact-reduxaxios

解决方案


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

// 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 文件不知道存储,而是导出设置器

// 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)
})

推荐阅读