store.subscribe()在状态更改时无法在助手服务功能中工作

时间:2019-05-07 05:54:23

标签: reactjs service redux

基本上,我在登录api响应中得到一个令牌,该令牌在网络请求中用作标头。我将此令牌存储在我的redux存储中。我将axios用于所有的api调用。我创建了一个axios实例,如下所示:

axios.js

const axiosInstance = axios.create({
    baseURL: 'http://localhost:3003',
    // timeout: 10000,
    headers: {
        Authorization: ~token~,
        environment: 'production'
    }
});

这样我就可以像这样:

const resp = await axiosInstance.get(`/log/dashboardchartdatafromdate=${dateData.dateRange.from}&todate=${dateData.dateRange.to}`);

我已经尝试在axios.js内订阅redux存储,如下所示:

import configureStore from '../store';

 configureStore().subscribe(() => {
    token = configureStore().getState().loginReducer.token; //access token here
    console.log(token);
 });

我的商店看起来像这样:

store.js

export default function configureStore(initialState) {
  const composeEnhancers = window.REDUX_DEVTOOLS_EXTENSION_COMPOSE || compose;
  return createStore(reducers, composeEnhancers(applyMiddleware(thunk)));
}

我的问题是代码块无法进行状态更改。在应用程序启动时只能运行一次。

我不确定是否可以像我尝试的那样在帮助服务功能内订阅商店。如果我做错了,请纠正我。

1 个答案:

答案 0 :(得分:1)

您的动作创建者只需要看起来像这样。您可以使用可选的getState()函数,该函数可作为thunk操作中的参数使用。与必须订阅您的商店相比,这是更好的选择。

axiosInstance.js:

export default const axiosInstance = (token) => {
   return axios.create({
       baseURL: 'http://localhost:3003',
       // timeout: 10000,
       headers: {
          Authorization: token,
          environment: 'production'
       }
   });
}

您的操作文件:

import axiosInstance from "./axiosInstance"


const getDashboardData = (dateData) => {
    return (dispatch, getState) => {
        const token = getState().loginReducer.token

        const resp = axiosInstance(token).get(`/log/dashboardchartdatafromdate=${dateData.dateRange.from}&todate=${dateData.dateRange.to}`);

    }
}