类型'((dispatch:Dispatch)=> void'的参数不能分配给'AnyAction'类型的参数

时间:2020-07-23 18:36:42

标签: reactjs redux async-await react-redux redux-thunk

错误本身:

(alias) deleteCategory(id: number): (dispatch: Dispatch<AnyAction>) => void
import deleteCategory
Argument of type '(dispatch: Dispatch) => void' is not assignable to parameter of type 'AnyAction'.
  Property 'type' is missing in type '(dispatch: Dispatch) => void' but required in type 'AnyAction'.ts(2345)

问题代码:

export function getCategoryList(
  categories: CategoryType[],
  dispatch: Dispatch
) {
  return categories.map((category: CategoryType) => ({
    ...category,
    onDelete: () => {
      dispatch(deleteCategory(category._id)); //FIXME: Fix this. Error Appears here
    },
  }));
}

deleteCategory的实现

export const deleteCategory = (id: number) => (dispatch: Dispatch) => {
  deleteCategoryAPI(id)
    .then(() => {
      dispatch({
        type: DELETE_CATEGORY,
        category: id,
      });
    })
    .catch((error) => console.error(error));
};

deleteCategoryAPI的实现

export async function addCategoryAPI(category: CategoryType) {
  return fetch(`${API_URL}/categories`, {
    method: "POST",
    body: JSON.stringify(category),
    headers: { "Content-Type": "application/json; charset=UTF-8" },
  }).then((response) => response.json());
}

我在这里使用有问题的代码:

const categoryList = getCategoryList(categoryState, dispatch);
...
return (
    <List
      dataSource={categoryList}
      renderItem={({ name, onDelete }) => (
        <List.Item>
          <CategoryItem name={name} onDelete={onDelete} />
        </List.Item>
      )}
    />
  );
function CategoryItem({ name, onDelete }: categoryItemPropsType) {
export type categoryItemPropsType = {
  name: string;
  onDelete: () => void;
};

可能是什么问题?为此花了几个小时。 有趣的是,当我在功能组件的其他地方调用dispatch(deleteCategory(category._id))时,例如它可以正常工作。.非常感谢!

1 个答案:

答案 0 :(得分:0)

起初,我可以考虑几种不同的方法,具体取决于您要投入多少精力,对所需的原始实现方式的正确程度以及所需键入的准确性。 / p>

  1. 最简单的实现和最真实的API(但类型不正确):

    // create your own dispatch function reference with custom typings
    export const dispatchStore = store.dispatch as typeof store.dispatch | Dispatch<any>
    
    // use custom typed dispatch (unfortunately, you can pass it almost `any`thing)
    dispatchStore(myThunk('id123'))
    
  2. 一个简单的实现,但是需要键入每个呼叫(并且键入仍然很差):

    // optional
    export const dispatchStore = store.dispatch
    
    // type each dispatch as any (not good if you need to use 'abort', etc)
    dispatchStore(myThunk('id123') as any)
    
  3. 此项目符号特定于Redux Toolkit,但可以轻松应用于第三方库(例如Redux)的大多数TypeScript输入问题。在使用redux-toolkit的情况下,可以创建对configureStorecreateSlice的引用,并根据您的选择操纵输入。在以下代码中,我将createSlice函数包装在createSlicePlus中,在幕后添加了一堆便捷逻辑,并增强了args和return类型。

    // convenience `request` wrapper around store `dispatch` that abstracts the rest
    const promise = counter.request.decrementThunk(500)
    // even the RTK thunk promise is typed appropriately
    promise.abort()
    

第三个示例的代码可以在here on Github中找到。