当我试图访问react组件中的存储时,@connect工作得很好。但我该如何在其他代码中访问它呢。例如:让我们说我想使用授权令牌来创建我的axios实例,可以在我的应用程序中全局使用,实现这一点的最佳方法是什么?

这是我的api。js

// tooling modules
import axios from 'axios'

// configuration
const api = axios.create()
api.defaults.baseURL = 'http://localhost:5001/api/v1'
api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here
api.defaults.headers.post['Content-Type'] = 'application/json'

export default api

现在我想从我的商店访问一个数据点,这是什么样子,如果我试图在一个react组件中使用@connect获取它

// connect to store
@connect((store) => {
  return {
    auth: store.auth
  }
})
export default class App extends Component {
  componentWillMount() {
    // this is how I would get it in my react component
    console.log(this.props.auth.tokens.authorization_token) 
  }
  render() {...}
}

有什么见解或工作流模式吗?


当前回答

你可以使用从createStore函数返回的store对象(它应该已经在应用程序初始化的代码中使用了)。然后,您可以使用该对象通过store. getstate()方法或store.subscribe(listener)订阅存储更新来获取当前状态。

您甚至可以将此对象保存到window属性,以便从应用程序的任何部分访问它(如果您真的需要它的话)。商店)

更多信息可以在Redux文档中找到。

其他回答

从调用createStore的模块导出存储。然后您可以放心,它将被创建并且不会污染全局窗口空间。

MyStore.js

const store = createStore(myReducer);
export store;

or

const store = createStore(myReducer);
export default store;

MyClient.js

import {store} from './MyStore'
store.dispatch(...)

或者如果你使用默认

import store from './MyStore'
store.dispatch(...)

对于多个存储用例

如果需要一个存储的多个实例,可以导出一个工厂函数。 我建议将其设置为异步(返回承诺)。

async function getUserStore (userId) {
   // check if user store exists and return or create it.
}
export getUserStore

在客户端(在异步块中)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

你可以根据我如何访问非反应组件的商店使用中间件?:

中间件

function myServiceMiddleware(myService) {
  return ({ dispatch, getState }) => next => action => {
    if (action.type == 'SOMETHING_SPECIAL') {
      myService.doSomething(getState());
      myService.doSomethingElse().then(result => dispatch({ type: 'SOMETHING_ELSE', result }))
    }
    return next(action);
  }
}

使用

import { createStore, applyMiddleware } from 'redux'
const serviceMiddleware = myServiceMiddleware(myService)
const store = createStore(reducer, applyMiddleware(serviceMiddleware))

进一步阅读:Redux Docs >中间件

这可能有点晚,但我认为最好的方法是使用axios.interceptors如下所示。导入url可能会根据项目设置而改变。

index.js

import axios from 'axios';
import setupAxios from './redux/setupAxios';
import store from './redux/store';

// some other codes

setupAxios(axios, store);

setupAxios.js

export default function setupAxios(axios, store) {
    axios.interceptors.request.use(
        (config) => {
            const {
                auth: { tokens: { authorization_token } },
            } = store.getState();

            if (authorization_token) {
                config.headers.Authorization = `Bearer ${authorization_token}`;
            }

            return config;
        },
       (err) => Promise.reject(err)
    );
}

导出我的store变量

export const store = createStore(rootReducer, applyMiddleware(ReduxThunk));

在action文件或者你的文件中需要导入这个(store)

Import {store} from "./path…";

这一步用函数从存储变量中获取状态

const state = store.getState();

获取你的app的所有状态

对于TypeScript 2.0,它看起来是这样的:

MyStore.ts

export namespace Store {

    export type Login = { isLoggedIn: boolean }

    export type All = {
        login: Login
    }
}

import { reducers } from '../Reducers'
import * as Redux from 'redux'

const reduxStore: Redux.Store<Store.All> = Redux.createStore(reducers)

export default reduxStore;

MyClient.tsx

import reduxStore from "../Store";
{reduxStore.dispatch(...)}