问题描述
所以我正在使用TS React,Redux和Thunk中间件来处理与我的api通信的redux动作,但是我似乎无法获得我的动作功能的初始配置。
我的动作功能如下:
export const startSession = ((accessCode: string) => {
return async (dispatch: Dispatch): Promise<Action> => {
try {
const response = await apiCall(accessCode);
return dispatch({ type: SessionActions.START_SESSION,payload: response });
} catch (e) {
console.log('error',e)
}
};
});
我也尝试过这个:
export const startSession = ((accessCode: string) => {
return async (dispatch: Dispatch) => {
try {
await apiCall(accessCode)
.then(response => dispatch({ type: SessionActions.START_SESSION,payload: response }))
} catch (e) {
console.log('error',e)
}
};
})
,但似乎都不起作用。我以为,等待api响应将迫使redux等待,但是它似乎正在将诺言恢复到状态-在我的redux-logger中显示:
action undefined @ 19:10:17.807
redux-logger.js?d665:1 prev state: {some state}
redux-logger.js?d665:1 action: Promise {<pending>}
我得到了错误:
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
我注意到此分派类型是未定义的,因此在从api返回数据之前必须首先进行一次分派调用。如果有人可以向我解释为什么这样做,以及编写使用thunk动作的标准格式会很有帮助。
也请让我知道是否缺少我的信息。
以下有人问我如何用thunk初始化存储:
import { createStore,applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { createBrowserHistory } from 'history';
import rootReducer from '../_reducers/index'
const loggerMiddleware = createLogger();
export const history = createBrowserHistory();
export const store = createStore(
rootReducer,applyMiddleware(
thunkMiddleware,loggerMiddleware
)
);
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)