首页 > 解决方案 > 将 useReducer 调度作为 typescript 中的 prop 向下传递,使用什么类型?

问题描述

const [state, dispatch] = useReducer(reducer, initialState);

return (
<Component dispatch={dispatch} />
)

// component file
const Component = ({dispatch}: ???) => ..... 

问号处应该填什么?

标签: reactjstypescriptreact-redux

解决方案


检查@types/react。我们可以看到有几个重载的定义useReducer,但是它会返回类型 Dispatch:https ://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L876

您可以Dispatch'react'.

请注意,这Dispatch是通用的。泛型类型表示分派操作的可能值。由你来定义这些,但 reducer 通常使用action.type.

import { Dispatch, FunctionComponent } from 'react';

interface ComponentProps {
  dispatch: Dispatch<{ type: string }>
}

const Component: FunctionComponent<ComponentProps> = ({ dispatch }) =>

推荐阅读