【问题标题】:Use custom middleware for async actions - when dipactching thunk action使用自定义中间件进行异步操作 - dipactching thunk 操作时
【发布时间】:2018-11-24 14:41:03
【问题描述】:

我不知道为什么这个给我带来了问题。我已经发送了很多 thunk,这应该是一个简单的。

这是我的商店:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
import logger from 'redux-logger';
import CircularJSON from 'circular-json';

let store;

const persistedState = localStorage.getItem('storeState') ?
                      JSON.parse(localStorage.getItem('storeState')):
                      {}

store = 
createStore(rootReducer,persistedState,applyMiddleware(thunk,logger));

这是动作创建者:

export async function fetchSrcContorlTrendChartData(){ 
 return async (dispatch)=>{
   let data = await getChartsData();
   dispatch({type:C.FETCH_SRC_CONTROL_TREND_CHART_DATA,payload:data})
  }
}//fetchS

这是 grtChartsData 函数:

export function getChartsData(){
  return {
    "labels": 
  ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
  "gitActiveReposByMonth":[1,4,6,7,7,7,9,10,24,56,45,23],
  "TFVCActiveReposByMonth":[23,18,15,15,15,6,17,12,23,12,8,3],
  }; 
 }//getChartsData

任何帮助都会非常感谢

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

    我阅读了您的代码,但我无法弄清楚您到底面临什么问题,或者您显示的代码与自定义中间件有什么关系?

    我看到的唯一问题是您正在使用 await 调用非异步函数“getChartsData()”,而您不需要

    你可以改成

    export function fetchSrcContorlTrendChartData() {
        return (dispatch)=>{
            let data = getChartsData();
            dispatch({type:C.FETCH_SRC_CONTROL_TREND_CHART_DATA,
               payload:data
            })
        }
    }//fetchS
    

    但更好的是,您实际上根本不需要 thunk

    export function fetchSrcContorlTrendChartData() {
        return {
            type: C.FETCH_SRC_CONTROL_TREND_CHART_DATA,
            payload: getChartsData();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 2020-10-01
      • 2018-09-21
      • 2018-01-30
      • 1970-01-01
      • 2018-05-09
      相关资源
      最近更新 更多