【问题标题】:TypeScript Ignoring Thunk- Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actionsTypeScript Ignoring Thunk- Unhandled Rejection (Error): Actions must be plain objects。使用自定义中间件进行异步操作
【发布时间】:2021-03-07 20:28:39
【问题描述】:

我已经在这个应用程序中安装了 Thunk。控制台日志显示一切工作一次,然后一切都停止工作。如何让 TypeScript 使用 Thunk?

代码: 像往常一样包含动作创建者的组件,还添加了道具接口以包含 Thunk 动作创建者:

interface Props {
  ThunkAC: Function
}

AC 抛出错误:

export const GetItems = async (dispatch: Dispatch, accessToken: string) : Promise<any> => {
  console.log('AC called')
  const config = {
    headers: { 
      'Authorization': `Bearer ${accessToken}`
    }
  };
  return async (dispatch: Dispatch) => {
    const response = await axios.get(itemsUrl, config);
      dispatch({
        type: ActionTypes.getItems,
        payload: response.data.Items
      })

  }
}

index.tsx:

const store = createStore(reducers, applyMiddleware(thunk));


//Provider
const app = (
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

ReactDOM.render(
  app,
  document.getElementById('root')
);

请告诉我使用 Thunk 作为中间件在 TypeScript 应用程序中返回函数时缺少什么。

【问题讨论】:

    标签: reactjs typescript redux react-redux redux-thunk


    【解决方案1】:

    对于每个对此感到沮丧的人,您不能仅通过向 Action Creators 添加显式类型来在 TypeScript 应用程序中添加 Thunk。它需要一个叫做 ThunkAction 的东西。

    GitHub上有很多例子。

    Action Creator 文件中的简要模板:

    import axios from 'axios';
    import { ThunkAction } from "redux-thunk";
    import { Action } from 'redux';
    import { initialState } from '../Reducers';
    import { ActionTypes } from '../Actions/types';
    
    export interface GetItem {
      type: ActionTypes.getItems;
      payload: ISavedItems;
    }
    
    export const items = (
      item: object
    ): ThunkAction<void, typeof initialState, null, Action<any>> => async dispatch => {
      const config = {
        headers: { 
          'Authorization': `Bearer ${accessToken}`
        }
      };
      const response = await axios.get(itemDB, config);
      dispatch<GetItem>({
        type: ActionTypes.getItems,
        payload: response.data.items
      })
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2016-12-20
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      相关资源
      最近更新 更多