reactjs - 从实用程序模块访问 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
未定义 - 导致我相信导入在实例化之前已解决?--:
未捕获的类型错误:无法读取未定义的属性“订阅”
解决方案
有几种方法可以解决这个问题,但一种简单的方法是使用函数来注入您的商店。
// 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)
})
推荐阅读
- ios - UIDatePicker 作为 UITextField 的 Inputview
- c++ - C ++ GUI按钮卡在底部
- angular - Angular在属性html中不起作用
- html - 如何已经编写了按钮更改代码?
- python - 对每组熊猫数据框进行排序并保持所需的顺序
- php - 带有 if(emtpy) 语句的 Foreach
- c - cygwin中的击键中断
- git - 在“git reset --hard #commit”之后,本地 Git 未与远程同步
- json - 将单个 json 文件中存在的 json 列表转换为单个有效 json
- php - PHP : 以电子邮件形式发送已填写表格的 PDF